Can't get ASP.NET 4 Web API to return Status Code "201 - Created" for successful POST

asp.net-mvc-4, asp.net-web-api

Solution

`HttpContext.Current` is a hangover from the past.

You need to define response as `HttpResponseMessage<T>`:

public HttpResponseMessage<MyResource> Post(MyResource myResource)
{
    .... // set the myResource
    return new HttpResponseMessage<MyResource>(myResource)
            {
                StatusCode = HttpStatusCode.Created
            };
}

UPDATE

As you might notice from the comments, this approach works with beta release. Not the RC.

Problem

I am trying to return an HTTP Status Code of `201 Created` for a RESTful POST operation using ASP.NET 4 Web API, but I always get a `200 OK`. I'm currently debugging on IIS 7.5.7600.16385, VS 2010 Professional, Windows 7 64-bit Professional. ``` public MyResource Post(MyResource myResource) { MyResource createdResource; ... HttpResponse response = HttpContext.Current.Response; response.ClearHeaders(); // added this later, no luck response.ClearContent(); // added this later, no luck response.StatusCode = (int)HttpStatusCode.Created; SetCrossOriginHeaders(response); return createdResource; } ``` I have seen other examples where `HttpContext.Current.Response.StatusCode` is set before returning data, so I didn't think this would be a problem. I haven't tracked it down in the MVC 4 source yet. (This is related to my investigations with this question but different enough topic to warrant its own question) I am not sure whether the problem is IIS or the Web API. I will do further tests to narrow it down.

Original source

Related problems