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
:
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?
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 .
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With