Asp.net mvc 4 Can';t获取ASP.NET 4 Web API以返回状态代码“;201-已创建;成功的职位

Asp.net mvc 4 Can';t获取ASP.NET 4 Web API以返回状态代码“;201-已创建;成功的职位,asp.net-mvc-4,asp.net-web-api,Asp.net Mvc 4,Asp.net Web Api,我试图返回一个HTTP状态代码201 Created,用于使用ASP.NET 4 Web API的RESTful POST操作,但我总是得到一个200 OK 我目前正在调试IIS 7.5.7600.16385,VS 2010 Professional,Windows7 64位Professional public MyResource Post(MyResource myResource) { MyResource createdResource; ... HttpRes

我试图返回一个HTTP状态代码201 Created,用于使用ASP.NET 4 Web API的RESTful POST操作,但我总是得到一个200 OK

我目前正在调试IIS 7.5.7600.16385,VS 2010 Professional,Windows7 64位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.StatusCode
,所以我认为这不会是一个问题。我还没有在MVC4源代码中找到它

(这与我的调查有关,但主题不同,足以证明自己的问题)


我不确定问题是IIS还是Web API。我将做进一步的测试来缩小范围。

HttpContext。当前的
是过去的遗留问题


您需要将响应定义为
HttpResponseMessage

公共httpresponsemessagepost(MyResource MyResource)
{
..//设置myResource
返回新的HttpResponseMessage(myResource)
{
StatusCode=HttpStatusCode.Created
};
}

更新 从评论中您可能会注意到,这种方法适用于beta版不是RC。

试试以下方法:

return Request.CreateResponse<MyResource>(HttpStatusCode.Created, createdResource);
返回请求.CreateResponse(HttpStatusCode.Created,createdResource);

谢谢!成功了。实际上,我只是返回HttpResponseMessage,以便在必要时返回不同的内容类型,但根据需要实例化HttpResponseMessage,这也解决了我的相关问题。@MikeJansen不要太习惯于t的HttpResponseMessage,因为它将在将来的构建中消失。请参阅@DarrelMiller-谢谢,我已转换为HttpRequestMessage.CreateResponse()
HttpResponseMessage
不能与类型参数一起使用。
return Request.CreateResponse<MyResource>(HttpStatusCode.Created, createdResource);