Asp.net-Mvc-4

無法讓 ASP.NET 4 Web API 返回狀態程式碼“201 - 已創建”以成功發布

  • February 10, 2017

我正在嘗試201 Created使用 ASP.NET 4 Web API 返回 RESTful POST 操作的 HTTP 狀態程式碼,但我總是得到一個200 OK.

我目前正在 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.StatusCode在返回數據之前設置的例子,所以我不認為這會是一個問題。我還沒有在 MVC 4 原始碼中找到它。

(這與我對這個問題的調查有關,但不同的主題足以保證自己的問題)

我不確定問題是 IIS 還是 Web API。我會做進一步的測試來縮小範圍。

HttpContext.Current是過去的宿醉。

您需要將響應定義為HttpResponseMessage<T>

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

更新

正如您可能從評論中註意到的那樣,這種方法適用於beta版本。不是RC。

嘗試這個:

return Request.CreateResponse<MyResource>(HttpStatusCode.Created, createdResource);

引用自:https://stackoverflow.com/questions/10357526