【问题标题】:ASP.NET Core routing return 404ASP.NET Core 路由返回 404
【发布时间】:2021-02-01 07:04:59
【问题描述】:

我正在使用 ASP.NET Core 3.1 创建一个 Web api,并尝试将 URL 路由到控制器。到目前为止,我有一个这样的基本控制器:

    [Route("abc")]
    [ApiController]
    public class ABCController : ControllerBase
    {
        // GET: abc/1234
        [HttpGet("{id}")]
        public async Task<ActionResult<string>> GetABCService(long id)
        {
              ...
        }
    }

当我输入 http://myurl/abc/1234 时,这会正确地将我引导到该页面。我想要连接的下一个控制器是这样的:

    [Route("xxx")]
    [ApiController]
    public class XXXController : ControllerBase
    {

        // GET: abc/1234/XXX
        [HttpGet("{id}")]
        public async Task<ActionResult<string>> GetXXXService(long id)
        {
              ...
        }
    }

当我输入 http://myurl/abc/1234/xxx 时,它总是给我 404。我通过像这样设置我的端点使第一个工作:

app.UseEndpoints(endpoints =>{
                endpoints.MapControllerRoute(
                    "abc",
                    "abc/{id}",
                    new {controller = "ABCController", action = "GetABCService"});

              //My current endpoint mapping for the second controller:
                endpoints.MapControllerRoute(
                    "xxx",
                    "abc/{id}/xxx",
                    new {controller = "XXXController", action = "GetXXXStatus" });
}

我不明白为什么我会在 http://myurl/abc/1234/xxx 得到 404。有什么见解吗?

【问题讨论】:

  • 尝试在"abc/{id}"之前编写"abc/{id}/xxx"的路由配置。

标签: c# asp.net-core asp.net-core-webapi asp.net-core-3.1 asp.net-apicontroller


【解决方案1】:

你想说XXXController先通过[Route("abc")]路由'abc'

[Route("abc")]
    [ApiController]
    public class XXXController : ControllerBase
    {
        [HttpGet("{id}/xxx")]
        public ActionResult<string> GetXXXService(long id)
        {
            return "ActionResult";
        }
       
    }

【讨论】:

    【解决方案2】:

    当您使用属性路由时,例如使用[Route][HttpGet(…)],则忽略基于约定的路由。因此,在为 API 控制器生成路由时,不会考虑您使用 MapControllerRoute 定义的路由模板。此外,使用[ApiController] 属性实际上启用了某些与API 相关的约定。其中一个约定是您只能对 API 控制器使用属性路由。

    因此,如果您的项目中只有 API 控制器,那么您可以省略 MapControllerRoute 调用。相反,您必须确保您的属性路由是正确的。

    在您的情况下,如果您希望路由 abc/1234/XXX 工作,那么您将不得不使用路由 abc/{id}/XXX

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多