Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 689
Mike Avatar asked Nov 15 '17 01:11

Mike


1 Answers

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);
like image 102
Nkosi Avatar answered Nov 06 '22 12:11

Nkosi