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

纵饮孤独 提交于 2019-12-06 21:55:17

问题


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?


回答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.




回答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);
}



回答3:


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

Source code




回答4:


My GET action has a route name

    [HttpGet("{id:int}", Name = "GetOrganizationGroupByIdRoute")]
    public async Task<IActionResult> Get(int id, CancellationToken cancellationToken = default(CancellationToken))
    {
        ...
    }

And my POST action uses that route name to return the URL

    [HttpPost]
    public async Task<HttpStatusCodeResult> Post([FromBody]OrganizationGroupInput input, CancellationToken cancellationToken = default(CancellationToken))
    {
        ...
        var url = Url.RouteUrl("GetOrganizationGroupByIdRoute", new { id = item.Id }, Request.Scheme, Request.Host.ToUriComponent());
        Context.Response.Headers["Location"] = url;
        ...
    }

Resulting response using Fiddler

Hope that helps.




回答5:


I use this simple approximation based on the Uri being served at the web server:

[HttpPost]
[Route("")]
public IHttpActionResult AddIntervencion(MyNS.MyType myObject) {
  return Created<MyNS.MyType>(Request.RequestUri + "/" + myObject.key, myObject);
}


来源:https://stackoverflow.com/questions/31957060/mvc-6-web-api-resolving-the-location-header-on-a-201-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!