asp.net-mvc-4 – 无法让ASP.NET 4 Web API返回状态代码“201 – Created”以成功发布POST

我试图使用ASP.NET 4 Web API为RESTful POST操作返回HTTP状态代码201,但我总是得到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;
}

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

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

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

解决方法

HttpContext.Current是过去的宿醉.

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

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

UPDATE

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

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...