ASP.NET vnext overriding status code set in controller. Is this a bug?

239 views Asked by At

I'm building a simple WebApi in asp.net vnext on a Mac. I've followed the example set in this tutorial but I'm having a problem where the response codes I set in my controller methods are being overridden

Take this method in my CrudController:

[HttpPost]
public void Post([FromBody]CrudObject crudObject)
{
   var url = Url.RouteUrl("GetByIdRoute", new {id = 1}, 
       Request.Scheme, Request.Host.ToUriComponent());
   Context.Response.StatusCode = 201;
   Context.Response.Headers["Location"] = url;
 }

When I curl this or hit it with PostMan I should see a 201 Created response and a Location header pointing me to another url. When I run this using kestrel I get the Location header but the response code is 204 No Content.

I assume this is the vnext middleware overriding my change to the status code. Is that right? If so, should it be overriding my status code or is it a bug? If it's the correct behaviour, how should I do a redirect?

1

There are 1 answers

1
Kiran On BEST ANSWER

The behavior of void returning action was recently changed to not convert to 204 status code. However, for you scenario you could use the CreatedAtRoute helper method(this actually creates a CreatedAtRouteResult) which sets the Location header.

[HttpPost]
public void Post([FromBody]CrudObject crudObject)
{
    return CreatedAtRoute(routeName: "GetByIdRoute", routeValues: new { id = 1 }, value: null);
}

Is it on purpose that you do not want to return the created object back to client? if not, you could modify the above code by not passing null to the value parameter.