c# - CreatedAtAction 结果为 "No route matches the sup

关于“No route matches the supplied values”错误的问题有很多,但我还没有在答案中找到任何解决方案:(

这是我的 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();
        }
    }
}

当 POST 到/api/v0/Widgets 时,新条目被添加到数据库,但返回 HTTP 500,并带有消息“System.InvalidOperationException:没有路由匹配提供的值。”。我的代码与 https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1 中的示例几乎相同,我不知道问题出在哪里。

最佳答案

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

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

关于c# - CreatedAtAction 结果为 "No route matches the supplied values",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62657448/

相关文章:

node.js - NodeMailer - G-Suite - 服务账户 - 以群组邮件形式发送

angular - 具有父/子关系的 Angular 组件中的通用类型定义

html - 如何禁用 Angular 匹配

google-apps-script - 如何使用 GAS 获取文档中的 URL 并将其替换为 UR

reactjs - 在 cookie 接受横幅后重新初始化 i18next 实例

python - 如何使用环境变量设置 boto3 连接超时和读取超时?

react-native - 当应用程序已经安装时,如何从 React Native 中的实际应用程

python - 线程 Tornado + flask 应用程序的正确方法是什么?

ios - 即使不再显示,SwiftUI View 也会不断更新

python-3.x - Python中存在数值数据时如何解决TypeError : 'No Num