mu88
mu88

Reputation: 5434

"No route matches the supplied values" once again

I'm using ASP.NET Core 3 Web API. When trying to set the location header for a created entity using CreatedAtAction, it fails with System.InvalidOperationException: No route matches the supplied values. All the answers I found so far on SO didn't solve my issue 😒 So I really hope somebody can help me.

Here is my controller:

[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}";
}

Upvotes: 1

Views: 149

Answers (1)

scharnyw
scharnyw

Reputation: 2686

This issue should be fixed by upgrading Microsoft.AspNetCore.Mvc.Versioning to version 4.2 or above. See this issue on GitHub. The reason is that before v4.2, API version is not handled as an ambient value during URL generation so it has to be explicitly provided. In other words, before v4.2 you have to write this:

[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);
}

Upvotes: 2

Related Questions