2012-07-17 63 views
3

我一直在寻找使用.net Web API编写Web服务,但我看到两种不同的方法来发送错误消息。第一种方法是用适当的HttpStatusCode集返回HttpResponseMessage,这样的事情:ASP.NET Web API返回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]; 
} 

有什么优势/使用任何一个的缺点?就可扩展性和性能而言,要么比其他更好?

+7

阅读格伦块的解释[HttpResponseMessage和HttpResponseException之间的区别是什么](http://stackoverflow.com/questions/10660721/what-is-the-difference-between-httpresponsemessage-and-httpresponseexception) – Martin4ndersen 2012-07-17 13:31:29

+0

啊,我没有'不要看那个帖子。这确实有很大的帮助!谢谢 :) – 2012-07-17 13:45:11

回答

0

如果有些人好奇我去哪个方向,我HttpResponseException去以下几个原因:

  • 这使得代码更易读的人谁是不熟悉WebAPIs(大多数人都知道,当你抛出一个异常,出事了)
  • 在我的测试HttpResponseExceptions更快返回,情况因人而异
  • 它更容易单元测试(只是断言,抛出了一个异常)
相关问题