[.Net] 關於 IHttpActionResult 和 HttpResponseMessage?

Web API 中提供了 HttpResponseMessage處理返回訊息,
HttpResponseMessage 用於返回一個來自於客戶端的請求結果訊息,你可以使用 HttpResponseMessage 自訂返回的內容,
另外HttpResponseException 則是以當發生例外時用來返回客戶端錯誤訊息,例如 Http Status 404 或 500。

在Web API 2 中提供了IHttpActionResult,判斷非同步建立 HttpResponseMessage 的命令。
直接看程式碼看如何使用吧。

(WebApi):

public HttpResponseMessage DoSomething(int id)
{
    var status = _Repository.doSomething(id);
    if (status)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    else
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

 (WebApi2):

public IHttpActionResult DoSomething(int id)
{
    var status = _Repository.doSomething(id);
    if (status)
    {
        //return new HttpResponseMessage(HttpStatusCode.OK);
        return Ok();
    }
    else
    {
        //throw new HttpResponseException(HttpStatusCode.NotFound);
        return NotFound();
    }
}

也可以把HttpResponseMessage 轉化成 IHttpActionResult回傳,
範例如下:

public IHttpActionResult SomeAction()
{
   IHttpActionResult response;
   //we want a 303 with the ability to set location
   HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
   responseMsg.Headers.Location = new Uri("http://xxxxxx.blah");
   response = ResponseMessage(responseMsg);
   return response;
}

 

 

Reference:

https://msdn.microsoft.com/zh-tw/library/system.web.http.ihttpactionresult(v=vs.118).aspx

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results