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

3

我一直在研究使用.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];
}

使用其中之一有优点/缺点吗?就可扩展性和性能而言,哪个更好?


7
阅读Glenn Block对HttpResponseMessage和HttpResponseException的区别的解释。 - Martin4ndersen
啊,我没看到那篇帖子。这确实帮了很多!谢谢 :) - joe_coolish
1个回答

0
如果有人好奇我选择了哪个方向,我选择了HttpResponseException,原因如下:
  • 对于不太熟悉WebAPI的人来说,它使代码更易读(大多数人知道当你抛出异常时,出了问题)
  • 在我的测试中,HttpResponseExceptions返回更快,但结果可能会有所不同
  • 更容易进行单元测试(只需断言是否抛出异常)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接