[英]ASP.NET Web API return HttpResponseMessage or throw error
I've been looking into writing a web service using the .net Web APIs, but I'm seeing two different approaches to sending error messages. 我一直在寻找使用.net Web API编写Web服务,但我看到了两种不同的方法来发送错误消息。 The first is to return an
HttpResponseMessage
with the appropriate HttpStatusCode
set, something like this: 第一种是使用适当的
HttpStatusCode
集返回一个HttpResponseMessage
,如下所示:
public HttpResponseMessage<string> Get()
{
...
// Error!
return new HttpResponseMessage<string>(System.Net.HttpStatusCode.Unauthorized);
}
And the other method is to just throw an HttpResponseException
, like this: 而另一种方法是抛出一个
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];
}
Are there any advantages/disadvantages to using either one? 使用任何一个都有任何优点/缺点吗? And in terms of scalability and performance, is either one better than the other?
在可扩展性和性能方面,要么比另一个更好?
In case anyone is curious which direction I went, I went with HttpResponseException
for several reasons: 如果有人好奇我去了哪个方向,我会使用
HttpResponseException
,原因有以下几点:
HttpResponseExceptions
return faster, YMMV HttpResponseExceptions
返回更快,YMMV
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.