问题
Using ASP.NET Core 2.0.0 Web API, I'm trying to build a controller to do a database insert. The information can be inserted into the database just fine, but returning a CreatedAtRoute throws an 'InvalidOperationException: No route matches the supplied values.' Everything I've found online so far says this was a bug with early pre-release versions of ASP.NET Core and has since been fixed, but I'm not really sure what to do about this. The following is my controller code:
[Produces("application/json")]
[Route("api/page")]
public class PageController : Controller
{
private IPageDataAccess _pageData; // data access layer
public PageController(IPageDataAccess pageData)
{
_pageData = pageData;
}
[HttpGet("{id}", Name = "GetPage")]
public async Task<IActionResult> Get(int id)
{
var result = await _pageData.GetPage(id); // data access call
if (result == null)
{
return NotFound();
}
return Ok(result);
}
[HttpPost]
public async Task<IActionResult> Create([FromBody] Page page)
{
if (page == null)
{
return BadRequest();
}
await _pageData.CreatePage(page); // data access call
// Return HTTP 201 response and add a Location header to response
// TODO - fix this, currently throws exception 'InvalidOperationException: No route matches the supplied values.'
return CreatedAtRoute("GetPage", new { PageId = page.PageId }, page);
}
Could anyone possibly shed some light on this for me?
回答1:
The parameters need to match the route values of the intended action.
In this case you need id
not PageId
return CreatedAtRoute(
actionName: "GetPage",
routeValues: new { id = page.PageId },
value: page);
来源:https://stackoverflow.com/questions/47298098/asp-net-core-createdatroute-no-route-matches-the-supplied-values