Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 246
MikeJansen Avatar asked Apr 27 '12 20:04

MikeJansen


People also ask

How do I return a status code from Web API?

HTTP Status Code 201 is used to return Created status i.e., when request is completed and a resource is created. Such HTTP Response it is returned using Created function. Optionally, you can also return, the URL where the object is created and also an object along with the HTTP Response Created.

What status code will you get for a successful API call?

200 The request is successful as the endpoint does exist and makes some internal validation, but the response has to include some information on why the access is denied.

How do I run a Web API code in Visual Studio?

You can run your API with Ctrl+F5 and open the Postman and write the address https://localhost:5001 (HTTPS) or https://localhost:5000.

How do I use IActionResult in Web API?

IActionResult Return Type in ASP.NET Core Web API: The IActionResult is an interface and it is used to return multiple types of data. For example, if you want to return NotFound, OK, Redirect, etc. data from your action method then you need to use IActionResult as the return type from your action method.


1 Answers

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.

like image 61
Aliostad Avatar answered Sep 20 '22 19:09

Aliostad