无法获得ASP.NET 4的Web API返回状态code" 201 - 创建"成功的POST [英] Can't get ASP.NET 4 Web API to return Status Code "201 - Created" for successful POST
问题描述
我试图返回 201创建
使用ASP.NET 4的Web API一个RESTful POST操作,但我总是得到一个<一个HTTP状态code code> 200 OK 。
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
.
我目前正在调试的IIS 7.5.7600.16385,VS 2010专业版,Windows 7 64位专业版。
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;
}
我看到其中 HttpContext.Current.Response.Status code
正在恢复数据之前设置其他的例子,所以我不认为这会是一个问题。我没有在MVC 4源跟踪它呢。
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.
的(这关系到我的调查与<一个href=\"http://stackoverflow.com/questions/10336733/different-return-types-for-asp-net-mvc-4-web-api\">this问题但不同的话题足够,以保证其自身的问题)的
(This is related to my investigations with this question but different enough topic to warrant its own question)
我不知道问题是否是IIS或Web API。我会做进一步的测试,以缩小它。
I am not sure whether the problem is IIS or the Web API. I will do further tests to narrow it down.
推荐答案
HttpContext.Current
是过去遗留下来的。
您需要定义响应,的Htt presponseMessage&LT; T&GT;
:
public HttpResponseMessage<MyResource> Post(MyResource myResource)
{
.... // set the myResource
return new HttpResponseMessage<MyResource>(myResource)
{
StatusCode = HttpStatusCode.Created
};
}
更新
你可能会从注释中发现,这种方法适用于测试版的释放。 不会的RC。
UPDATE
As you might notice from the comments, this approach works with beta release. Not the RC.
这篇关于无法获得ASP.NET 4的Web API返回状态code&QUOT; 201 - 创建&QUOT;成功的POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!