Asp.Net Core 3.0 CreatedAtAction returns "no route matches the supplied values" 当动作名称以 "Async" 结尾时

Asp.Net Core 3.0 CreatedAtAction returns "no route matches the supplied values" when Action name ends with "Async"

我在使用 CreatedAtAction 时遇到了一个奇怪的问题,如果我的方法名称以 "Async" 关键字结尾,当我从我的 Add 方法中 return CreatedAtAction 时,我会收到 500 错误 "no route matches the supplied values"。如果我把其他任何东西作为方法名称,如 GetRatePlanAs、GetRatePlanAsyncA 或 GetRatePlan,那么它就像一个魅力。

如果我添加 [ActionName("GetRatePlanAsync")] 也可以,但我不想这样做。

CreatedAtAction:

return CreatedAtAction(nameof(GetRatePlanAsync), new { ... }, null);

无效:

    [HttpGet]
    [Route("item")]
    public async Task<ActionResult> GetRatePlanAsync(...)

作品:

    [HttpGet]
    [Route("item")]
    [ActionName("GetRatePlanAsync")]
    public async Task<ActionResult> GetRatePlanAsync(...)

同时工作:

    [HttpGet]
    [Route("item")]
    public async Task<ActionResult> GetRatePlan(...)

经过几个小时的测试,我找到了这些文章: https://github.com/aspnet/AspNetCore/issues/15316 and https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#async-suffix-removal-from-controller-action-names

简而言之,这是 Asp.Net Core 3.0 中的重大变化。

我真正喜欢的一个解决方案是在 Configure Services Startup 中将 options.SuppressAsyncSuffixInActionNames 设置为 false:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(options => options.SuppressAsyncSuffixInActionNames = false);

        ...
    }