![](/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.