c# - CreateAtAction 在 ASP.Net Web API 中返回“没有路由与提供的值匹配”
问题描述
我有以下 Put 方法来更新我的项目::
[HttpPut]
[Route("items")]
public async Task<IActionResult> UpdateProduct([FromBody] CatalogItem productToUpdate)
{
var catalogItem = await _catalogContext.CatalogItems.SingleOrDefaultAsync(i => i.Id == productToUpdate.Id);
if (catalogItem == null) return NotFound(new { Message = $"Item with id {productToUpdate.Id} not found." });
catalogItem = productToUpdate;
_catalogContext.CatalogItems.Update(catalogItem);
await _catalogContext.SaveChangesAsync();
return CreatedAtAction(nameof(GetItemById), new { id = productToUpdate.Id }, productToUpdate);
}
以及以下 GetItemBy Id 操作:
[HttpGet]
[Route("items/{id:int}")]
public async Task<IActionResult> GetItemById(int id)
{
if (id <= 0)
{
return BadRequest();
}
var item = await _catalogContext.CatalogItems.SingleOrDefaultAsync(c => c.Id == id);
if (item != null)
{
return Ok(item);
}
return NotFound();
}
当我通过这个对象大摇大摆地调用更新操作时:
{
"id": 42,
"name": "TestProduct",
"description": "this is a test",
"price": 12.55,
"imageFileName": null,
"imagePath": null,
"catalogTypeId": 1,
"catalogBrandId": 2
}
我收到此错误:
应用程序引发了未处理的异常。目录api | System.InvalidOperationException:没有路由与提供的值匹配。
该项目在数据库中更新,但执行 CreatedAtAction 时出现错误。我在 POST 操作中遇到了同样的问题。我尝试使用 CreatedAtRoute,甚至在没有第三个参数 productToUpdate 的情况下尝试了它。我可以毫无问题地调用 GetItemById (/api/Catalog/items/42)...
我在这里有什么遗漏吗?
解决方案
得到工作吗?如果是这样,请将 put 上的路线更改为与 get 相同。
推荐阅读
- python - 如何让我的逻辑回归运行得更快?
- javascript - 每 x 秒刷新一次 DIV,无需重新加载页面
- swift - 在 Int 附加数组中转换字符串(数字) - Swift
- java - 我使用 gRPC 生成 java 代码“@javax.annotation.Generated”,它报告“错误:(20,18)java:找不到符号”。如何解决?
- c# - 循环遍历集合时 foreach 迭代器 null
- angular - Custom Formcomponent with ControlValueAccessor/Validator has asynchronous update of control inside validate
- javascript - 将数据发布到 expressjs 的简单 xmlhttprequest 问题
- multithreading - What happens if all puma's threads are handling a request and a new connection attempt happens?
- node.js - puppeteer on popup dialog/modal
- python-xarray - Xarray get matching variable names between two datasets