首页 > 解决方案 > ASP.NET Core 路由无法匹配路由参数,API 资源管理器中的路由参数重复

问题描述

有这个代码:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

[Route("/api/intakes/{​​​​​​​​intakeId}​​​​​​​​/employees/")]
[ApiController]
public class EmployeesController : ControllerBase
{
    [HttpGet]
    public async Task<IReadOnlyCollection<object>> GetEmployees([FromRoute]int intakeId)
    {
        return new[] { new { a = "asdsf", id = intakeId } };
    }
}

我正在尝试访问GET /api/intakes/5/employees/,但路由不匹配。

日志:

Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/1.1 GET http://localhost:5000/api/intakes/5/employees/ - -
Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware: Trace: All hosts are allowed.
Microsoft.AspNetCore.Routing.Matching.DfaMatcher: Debug: 1 candidate(s) found for the request path '/api/intakes/5/employees/'
Microsoft.AspNetCore.Routing.Matching.DfaMatcher: Debug: Endpoint 'WebApplication3.EmployeesController.GetEmployees (WebApplication3)' with route pattern 'api/intakes/{​​​​​​​​intakeId}​​​​​​​​/employees' was rejected by complex segment '{​​​​​​​​intakeId}​​​​​​​​' for the request path '/api/intakes/5/employees/'
Microsoft.AspNetCore.Routing.Matching.DfaMatcher: Debug: Endpoint 'WebApplication3.EmployeesController.GetEmployees (WebApplication3)' with route pattern 'api/intakes/{​​​​​​​​intakeId}​​​​​​​​/employees' is not valid for the request path '/api/intakes/5/employees/'
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware: Debug: Request did not match any endpoints

奇怪的是,在 API 资源管理器中,我可以看到intakeId这条路线的 2 个参数

API 浏览器

标签: asp.net-core.net-coreasp.net-core-5.0.net-5

解决方案


您可以尝试应用路由约束来限制参数intakeId,如下所示。

[Route("api​​​​​​​​/intakes/{intakeId:int}/employees/")]
[ApiController]
public class EmployeesController : ControllerBase
{

推荐阅读