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];
}
有什么优势/使用任何一个的缺点?就可扩展性和性能而言,要么比其他更好?
阅读格伦块的解释[HttpResponseMessage和HttpResponseException之间的区别是什么](http://stackoverflow.com/questions/10660721/what-is-the-difference-between-httpresponsemessage-and-httpresponseexception) – Martin4ndersen 2012-07-17 13:31:29
啊,我没有'不要看那个帖子。这确实有很大的帮助!谢谢 :) – 2012-07-17 13:45:11