![](/img/trans.png)
[英]ASP.NET Web API Conditionally return 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
,原因有以下幾點:
HttpResponseExceptions
返回更快,YMMV
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.