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

14,940

Solution 1

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.

Solution 2

In the new ASP.NET MVC Core there is a property Url, which returns an instance of IUrlHelper. You can use it to generate a local URL by using the following:

[HttpPost]
public async Task<IActionResult> Post([FromBody] Person person)
{
  _DbContext.People.Add(person);
  await _DbContext.SaveChangesAsync();

  return Created(Url.RouteUrl(person.Id), person.Id);
}

Solution 3

There is an UrlHelper class which implements IUrlHelper interface. It provides the requested functionality.

Source code

Share:
14,940

Related videos on Youtube

Dave New
Author by

Dave New

Updated on November 08, 2020

Comments

  • Dave New
    Dave New over 3 years

    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?

  • Dblock247
    Dblock247 over 8 years
    You can just do [HttpPost("")]. just a small shortcut i wanted to add.
  • Kiruahxh
    Kiruahxh about 3 years
    You should use nameof(GetClient) to avoid future refactoring bugs.