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

时间:2012-07-17 13:23:45

标签: asp.net asp.net-web-api

我一直在寻找使用.net Web API编写Web服务,但我看到了两种不同的方法来发送错误消息。第一种是使用适当的HttpResponseMessage集合返回HttpStatusCode,如下所示:

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];
}

使用任何一个都有任何优点/缺点吗?在可扩展性和性能方面,要么比另一个更好?

1 个答案:

答案 0 :(得分:0)

如果有人好奇我走了哪个方向,我会选择HttpResponseException,原因如下:

  • 它使代码对于不熟悉WebAPI的人更具可读性(大多数人都知道当你抛出异常时出错了)
  • 在我的测试中HttpResponseExceptions返回更快,YMMV
  • 单元测试更简单(只是假设抛出异常)