ASP.NET 8 API中CreatedAtAction返回路由匹配失败问题求助
ASP.NET 8 API中CreatedAtAction跳转Get请求报错问题
在ASP.NET 8 API的Post或Put请求中使用CreatedAtAction跳转至Get请求时,始终返回错误信息:"No route matches the supplied values."
已尝试的解决方法
- 为Get方法添加
[ActionName(nameof([目标Action名称]))]特性 - 为HttpGet特性设置Name属性,示例如下:
[HttpGet("{variable}", Name = nameof([目标Action名称]))][HttpGet("{variable}", Name = "[唯一标识名称]")]
- 同时组合使用上述两种特性配置
代码示例
[Route("[controller]")] [ApiController] public class AreaController : ControllerBase { // 配置方式1 // [HttpGet("{variable}", Name = nameof(GetSomething))] // 配置方式2 // [HttpGet("{variable}", Name = "GetSomethingById")] // 搭配ActionName特性 // [ActionName(nameof(GetSomething))] public async Task<ActionResult<YourClass>> GetSomething(int variable) { // 业务逻辑实现 } [HttpPost] public async Task<ActionResult<YourClass>> PostSomething(YourClass pass) { // 已尝试的返回写法 // return CreatedAtAction(nameof(GetSomething), new { variable = pass.Id }); // return CreatedAtAction("GetSomethingById", new { variable = pass.Id }); // return CreatedAtAction(nameof(GetSomething), new { variable = pass.Id }, pass); // return CreatedAtAction("GetSomethingById", new { variable = pass.Id }, pass); } }
特殊情况说明
使用CreatedAtAction([名称], new { variable = pass.Id }, pass)形式时,接口仅返回pass对象,并未跳转到对应的Get请求;其他返回方式则仍会触发**"No route matches the supplied values."**错误。
已尝试多种常规解决方案,但问题仍未得到解决。
内容的提问来源于stack exchange,提问作者motaz allala
相关产品推荐
相关产品推荐

