无法让ASP.NET 4 Web API为成功POST返回状态代码"201 - Created"

Mik*_*sen 8 asp.net-mvc-4 asp.net-web-api

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

我目前正在调试IIS 7.5.7600.16385,VS 2010 Professional,Windows 7 64位专业版.

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;
}
Run Code Online (Sandbox Code Playgroud)

我已经看到HttpContext.Current.Response.StatusCode在返回数据之前设置的其他示例,所以我认为这不是问题.我还没有在MVC 4源代码中找到它.

(这与我对这个问题的调查有关,但有足够的主题来保证自己的问题)

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

Ali*_*tad 10

HttpContext.Current 是过去的宿醉.

您需要将响应定义为HttpResponseMessage<T>:

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

UPDATE

正如您在评论中可能注意到的那样,此方法适用于测试版.不是 RC.

  • @MikeJansen不要太习惯T的HttpResponseMessage <T>,因为它在将来的版本中会消失.请参见http://aspnetwebstack.codeplex.com/discussions/350492 (2认同)