加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – 无法让ASP.NET 4 Web API返回状态代码“201 –

发布时间:2020-12-16 04:25:57 所属栏目:asp.Net 来源:网络整理
导读:我试图使用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; ...
我试图使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读