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. The first is to return an HttpResponseMessage
with the appropriate HttpStatusCode
set, something like this:
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:
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:
HttpResponseExceptions
return faster, YMMV
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.