【问题标题】:"No route matches the supplied values" once again再次“没有路线与提供的值匹配”
【发布时间】:2021-04-07 13:55:47
【问题描述】:

我正在使用 ASP.NET Core 3 Web API。尝试使用CreatedAtAction 为创建的实体设置位置标头时,它失败并显示System.InvalidOperationException: No route matches the supplied values. 到目前为止我在SO 上找到的所有答案都没有解决我的问题????所以我真的希望有人可以帮助我。

这是我的控制器:

[ApiVersion("1.0")]
[Route(ApiVersionSegment + "/<<domain-specific resource name>>/")]
public class DomainController : BaseApiController
{
    private const string ReportsSegment = "reports";

    [HttpGet(ReportsSegment + "/{reportId}")]
    public ActionResult<ReportModel> GetReport(int reportId)
    {
        // ...
    }

    [HttpPost(ReportsSegment)]
    public ActionResult<ReportModel> CreateReport()
    {
        // ...

        var entity = new ReportModel { ReportId = 2 };
        return CreatedAtAction(nameof(GetReport), new { reportId = entity.ReportId }, entity);
    }

    // there are some more actions which belong to the same domain, but are not located
    // under the ReportsSegment. I left them out for brevity.
}

[Route(ApiVersionSegment + "/[controller]/")]
[ApiController]
public class BaseApiController : ControllerBase
{
    protected const string ApiVersionSegment = "v{version:apiVersion}";
}

【问题讨论】:

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


    【解决方案1】:

    应该通过将Microsoft.AspNetCore.Mvc.Versioning 升级到 4.2 或更高版本来解决此问题。请参阅 GitHub 上的 this issue。原因是在 v4.2 之前,API 版本在 URL 生成期间不作为环境值处理,因此必须显式提供。换句话说,在 v4.2 之前你必须这样写:

    [HttpPost(ReportsSegment)]
    public ActionResult<ReportModel> CreateReport(ApiVersion apiVersion)
    {
        // ...
    
        var entity = new ReportModel { ReportId = 2 };
        return CreatedAtAction(nameof(GetReport), new { reportId = entity.ReportId, version = apiVersion.ToString() }, entity);
    }
    

    【讨论】:

    • 谢谢!将Microsoft.AspNetCore.Mvc.Versioning更新到5.0.0后,问题就消失了??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2019-08-21
    相关资源
    最近更新 更多