Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Dave New Avatar asked Aug 12 '15 05:08

Dave New


People also ask

How do I add a header in Web API?

Adding Custom Header for Individual Response We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response object through the HttpContext object. Then, we add a new header, with the name of x-my-custom-header and a value of individual response .

Which header should the client use in the response for information about the newly created resource?

After a resource has been created successfully, the server should respond with HTTP 201 (Created). The response should also have a Location header that contains the URI of the newly created resource. When needed, the response body can contain the created resource. In this case, a Content-Type header is also required.

What is ActionResult in Web API?

ActionResult<T> type ASP.NET Core includes the ActionResult<T> return type for web API controller actions. It enables you to return a type deriving from ActionResult or return a specific type.

How do I return a view from Web API action?

So, if you want to return a View you need to use the simple ol' Controller . The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage ( View ) for a user you don't use the Web API.


Video Answer


2 Answers

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.

like image 111
Dave New Avatar answered Sep 18 '22 15:09

Dave New


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);
}
like image 36
Shimmy Weitzhandler Avatar answered Sep 20 '22 15:09

Shimmy Weitzhandler