CreatedAtAction结果为“没有路由与提供的值匹配”

时间:2020-06-30 12:26:49

标签: c# asp.net-core

关于“没有路线与提供的值匹配”错误有很多问题,但是我还没有在答案中找到任何解决方案:(

这是我的控制者:

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

在POST到/ api / v0 / Widgets时,新条目将添加到数据库中,但是返回HTTP 500,并显示消息“ System.InvalidOperationException:没有路由与提供的值匹配。”。我的代码与https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1中的示例几乎完全相同,但我对可能出现的问题不知所措。

1 个答案:

答案 0 :(得分:0)

您需要在CreatedAtAction方法中指定api版本,如下所示:

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