简体   繁体   English

ASP.NET Web API返回HttpResponseMessage或抛出错误

[英]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 ,原因有以下几点:

  • It makes the code more readable to someone who is not as familiar with WebAPIs (Most people know that when you throw an exception, something went wrong) 它使代码对于不熟悉WebAPI的人更具可读性(大多数人都知道当你抛出异常时出错了)
  • In my tests HttpResponseExceptions return faster, YMMV 在我的测试中, HttpResponseExceptions返回更快,YMMV
  • It's easier to Unit Test (just Assert that an exception was thrown) 单元测试更简单(只是断言抛出异常)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM