首页 > 解决方案 > 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)...

我在这里有什么遗漏吗?

标签: c#asp.netapi.net-core

解决方案


得到工作吗?如果是这样,请将 put 上的路线更改为与 get 相同。


推荐阅读