简体   繁体   中英

ASP.NET Core CreatedAtRoute No route matches the supplied values

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?

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

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