Web API使用HttpResponseMessage與HttpResponseException的差異 HttpResponseMessage 返回類型


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

  其實用 HttpResponseMessage 也能夠返回 404、500 等錯誤,那為何還需要使用 HttpResponseException 來返回錯誤? 參考此文章 提出了一個觀點,文章中提到當呼叫 Web API 服務時發生了與預期上不同的錯誤時,理當應該中止程序返回錯誤訊息,這時對於錯誤的返回就該使用 HttpResponseException,而使用 HttpResponseMessage 則是代表着當客戶端發送了一個工作請求而 Web API 正確的完成了這個工作,就能夠使用 HttpResponseMessage 返回一個 201 的訊息,所以 HttpResponseMessage 與 HttpResponseException 在使用上根本的目標就是不同的,用 HttpResponseMessage 去返回一個例外錯誤也會讓程序結構難以辨別且不夠清晰,接着讓我們看一下 HttpResponseMessage 與 HttpResponseException 的操作方式。 www.it165.net


HttpResponseMessage

  HttpResonseMessage 用來響應訊息並包含狀態碼及數據內容,如需要返回一個 HttpResonseMessage 的實例可以使用 Request 的擴充功能 CreateResponse 方法,如下

 

public HttpResponseMessage DeleteProductById(int id)
{
      return Request.CreateResponse(HttpStatusCode.OK);
}

當然也可以自行定義響應的狀態碼及數據內容,如下

public HttpResponseMessage DeleteProductById(int id)
{
    // do something...
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.StatusCode = HttpStatusCode.OK;
    response.Content = new StringContent("Delete Success!");    // 響應內容
    return response;
}

如果需要響應列舉對象可以使用 ObjectContent<T>,如下

public HttpResponseMessage GetAllProducts()
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

    response.Content = new ObjectContent<IEnumerable<product>>(new ProductDao().GetProducts(),new JsonMediaTypeFormatter());
    return response;
}

另外 CreateResponse 擴充方法也提供了 CreateResponse<T> 泛型的回應方法 ,如下

public HttpResponseMessage GetProductById(int id)
{
    IEnumerable<product> products = new ProductDao().GetProducts();
    var product = products.Where(p => p.Id == id);
    if (product.FirstOrDefault<product>() != null)
        return Request.CreateResponse<Product>(HttpStatusCode.OK, product.First<Product>());
    else
        throw new HttpResponseException(HttpStatusCode.NotFound);
}

HttpResponseException

  HttpResponseException 為處理例外之用,能夠將指定的 HttpResponseMessage 返回至客戶端,在客戶端呼叫 Web API 發生錯誤時,客戶端並不會得到一個空值或錯誤畫面,故需要將錯誤包裝成回復訊息而最基本的情況下可以只回復狀態碼,如下。

public HttpResponseMessage GetAllProducts()
{
    throw new HttpResponseException(HttpStatusCode.NotFound);
}

當然也能夠自己定義錯誤訊息內容,如下

public HttpResponseMessage PutProduct(int id, string name, string category, string price, int stock)
{
  ProductDao productDao = new ProductDao();
 
  if (productDao.UpdateProduct(id, name, category, price, stock))
    return Request.CreateResponse(HttpStatusCode.OK);
  else
  {
    var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {       Content
= new StringContent("Update Product Error"),
      ReasonPhrase
= "Server Error"
    
};
    
throw new HttpResponseException(response);
  } }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM