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

我们两清 提交于 2019-12-05 02:46:13
Dave New

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

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

Source code

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.

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