簡體   English   中英

ASP.NET Web API返回HttpResponseMessage或拋出錯誤

[英]ASP.NET Web API return HttpResponseMessage or throw error

我一直在尋找使用.net Web API編寫Web服務,但我看到了兩種不同的方法來發送錯誤消息。 第一種是使用適當的HttpStatusCode集返回一個HttpResponseMessage ,如下所示:

public HttpResponseMessage<string> Get() 
{ 
      ...
      // Error!
      return new HttpResponseMessage<string>(System.Net.HttpStatusCode.Unauthorized); 
}

而另一種方法是拋出一個HttpResponseException ,如下所示:

public Person Get(int id)
{
     if (!_contacts.ContainsKey(id))
     {
         throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("Contact {0} not found.", id)));
     }

     return _contacts[id];
}

使用任何一個都有任何優點/缺點嗎? 在可擴展性和性能方面,要么比另一個更好?

如果有人好奇我去了哪個方向,我會使用HttpResponseException ,原因有以下幾點:

  • 它使代碼對於不熟悉WebAPI的人更具可讀性(大多數人都知道當你拋出異常時出錯了)
  • 在我的測試中, HttpResponseExceptions返回更快,YMMV
  • 單元測試更簡單(只是斷言拋出異常)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM