Asp.Net核心区域路由到Api控制器无法正常工作

问题描述 投票:0回答:1

我在一个区域中托管了一个API控制器。但是,路由似乎不起作用,因为我的ajax调用在尝试命中控制器操作时继续返回404。控制器构造函数中的断点永远不会被命中。

[Area("WorldBuilder")]
[Route("api/[controller]")]
[ApiController]
public class WorldApiController : ControllerBase
{
    IWorldService _worldService;
    IUserRepository _userRepository;

    public WorldApiController(IWorldService worldService, IUserRepository userRepository)
    {
        _worldService = worldService;
        _userRepository = userRepository;
    }

    [HttpGet]
    public ActionResult<WorldIndexViewModel> RegionSetSearch()
    {
        string searchTerm = null;
        var userId = User.GetUserId();
        WorldIndexViewModel model = new WorldIndexViewModel();
        IEnumerable<UserModel> users = _userRepository.GetUsers();
        UserModel defaultUser = new UserModel(new Microsoft.AspNetCore.Identity.IdentityUser("UNKNOWN"), new List<Claim>());
        model.OwnedRegionSets = _worldService.GetOwnedRegionSets(userId, searchTerm);
        var editableRegionSets = _worldService.GetEditableRegionSets(userId, searchTerm);
        if (editableRegionSets != null)
        {
            model.EditableRegionSets = editableRegionSets.GroupBy(rs =>
                (users.FirstOrDefault(u => u.IdentityUser.Id == rs.OwnerId) ?? defaultUser)
                    .IdentityUser.UserName)
            .Select(g => new RegionSetCollectionModel(g)).ToList();
        }
        var viewableRegionSets = _worldService.GetViewableRegionSets(userId, searchTerm);
        if (viewableRegionSets != null)
        {
            model.ViewableRegionSets = viewableRegionSets.Where(vrs => vrs.OwnerId != userId).GroupBy(rs =>
                    (users.FirstOrDefault(u => u.IdentityUser.Id == rs.OwnerId) ?? defaultUser)
                        .IdentityUser.UserName)
                .Select(g => new RegionSetCollectionModel(g)).ToList();
        }
        return model;
    }
}

和我的startup.cs文件:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {


        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {

            routes.MapRoute(name: "areaRoute",
              template: "{area}/{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
    }
}

我试过以下ajax地址:

   localhost:44344/api/WorldApi/RegionSetSearch
   localhost:44344/WorldBuilder/api/WorldApi/RegionSetSearch
   localhost:44344/api/WorldBuilder/WorldApi/RegionSetSearch
   localhost:44344/WorldBuilder/WorldApi/RegionSetSerarch

对于我尝试的最后一个地址,我从控制器上的Route数据注释中删除了“api /”。

我不确定我在这里做错了什么。我正在关注我在网上找到的所有例子。

asp.net-core-mvc asp.net-core-2.0 asp.net-mvc-areas
1个回答
1
投票

MVC中有两种路由类型,conventions routing用于mvc,route attribute routing用于web api。

对于在conventions routings中为MVC配置的区域,不应与路由属性组合。 Route属性将覆盖默认的约定路由。

如果你更喜欢attribute routing,你可以

[Route("WorldBuilder/api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet("RegionSetSearch")]
    public ActionResult<IEnumerable<string>> RegionSetSearch()
    {
        return new string[] { "value1", "value2" };
    }        
}

注意[HttpGet("RegionSetSearch")],它定义了RegionSetSearch的动作,并在URL中添加占位符。

请求是qazxsw poi

如果你更喜欢https://localhost:44389/worldbuilder/api/values/RegionSetSearch,你可以删除conventions routingRoute之类的

ApiController

通过这种方式,您需要更改[Area("WorldBuilder")] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> RegionSetSearch() { return new string[] { "value1", "value2" }; } }

UseMvc

请求是app.UseMvc(routes => { routes.MapRoute("areaRoute", "{area:exists}/api/{controller}/{action}/{id?}"); });

© www.soinside.com 2019 - 2024. All rights reserved.