我一直在研究使用.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];
}
使用其中之一有优点/缺点吗?就可扩展性和性能而言,哪个更好?