简体   繁体   中英

CreateAtAction returns “No route matches the supplied values” in ASP.Net Web API

I have the following Put Method to update my Item::

[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);
}

And the following GetItemBy Id Action:

[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();
}

When I call the Update action via swagger with this object:

{
  "id": 42,
  "name": "TestProduct",
  "description": "this is a test",
  "price": 12.55,
  "imageFileName": null,
  "imagePath": null,
  "catalogTypeId": 1,
  "catalogBrandId": 2
}

I get this error:

An unhandled exception was thrown by the application. catalogapi | System.InvalidOperationException: No route matches the supplied values.

The item is updated in the database, but the error occurs when CreatedAtAction is executed. I have the same problem in my POST action. I tried to use CreatedAtRoute and even tried it without the third parameter productToUpdate. I can call the GetItemById (/api/Catalog/items/42) without any problem...

Is there anything I am missing here?

Does the get work? If so, change the route on the put to the same as the get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM