【问题标题】:ASP.NET Core routing fails to match route parameter, duplicated route parameter in API explorerASP.NET Core 路由无法匹配路由参数,API 资源管理器中的路由参数重复
【发布时间】:2021-06-17 14:20:16
【问题描述】:

拥有此代码:

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 explorer 中我可以看到这条路由的 2 个intakeId 参数

【问题讨论】:

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


    【解决方案1】:

    您可以尝试应用route constraint 来限制参数intakeId,如下所示。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多