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.
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.
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.
You can run your API with Ctrl+F5 and open the Postman and write the address https://localhost:5001 (HTTPS) or https://localhost:5000.
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.
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
};
}
As you might notice from the comments, this approach works with beta release. Not the RC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With