CreatedAtAction results in "No route matches the supplied values"

Viewed 248

There are huge numbers of questions about the "No route matches the supplied values" error, but I have not yet found any solutions among the answers :(

Here is my controller:

[ApiVersion("0.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class WidgetsController : ControllerBase
{
    private readonly IRepository _repository;

    public WidgetsController(IRepository repository)
    {
        _repository = repository;
    }

    [HttpPost]
    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public IActionResult Add([FromBody] AddWidgetRequest request)
    {
        WidgetDetails details;
        try
        {
            details = request.ToWidgetDetails();
        }
        catch (AddWidgetRequest.BadRequest e)
        {
            return BadRequest(e.Message);
        }

        var id = _repository.AddWidget(details);

        return CreatedAtAction(nameof(GetById), new {id = id}, details.WithId(id));
    }

    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public IActionResult GetById(int id)
    {
        if (_repository.TryGetWidget(id, out var details))
        {
            return Ok(details.WithId(id));
        }
        else
        {
            return NotFound();
        }
    }
}

When POSTing to /api/v0/Widgets, the new entry is added to the database, but HTTP 500 is returned, with message "System.InvalidOperationException: No route matches the supplied values.". My code is almost identical to the example in https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1, I'm at a loss as to what the issue could be.

1 Answers

You need specify the api version in the CreatedAtAction method like below:

public IActionResult Add([FromBody] AddWidgetRequest request,ApiVersion version)
{
    return CreatedAtAction(nameof(GetById), new { id = 1, version = version.ToString() }, details.WithId(id));
}
Related