gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:05:53 30 4
gpt4 key购买 nike

关于“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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com