asp.net-coreasp.net-core-mvcdnx

MVC 6 Web Api: Resolving the location header on a 201 (Created)


In Web Api 2.2, we could return the location header URL by returning from controller as follows:

return Created(new Uri(Url.Link("GetClient", new { id = clientId })), clientReponseModel);

Url.Link(..) would resolve the resource URL accordingly based on the controller name GetClient:

Location header

In ASP.NET 5 MVC 6's Web Api, Url doesn't exist within the framework but the CreatedResult constructor does have the location parameter:

return new CreatedResult("http://www.myapi.com/api/clients/" + clientId, journeyModel);

How can I resolve this URL this without having to manually supply it, like we did in Web API 2.2?


Solution

  • I didn't realise it, but the CreatedAtAction() method caters for this:

    return CreatedAtAction("GetClient", new { id = clientId }, clientReponseModel);
    

    Ensure that your controller derives from MVC's Controller.