【问题标题】:ASP.NET Web API return HttpResponseMessage or throw errorASP.NET Web API 返回 HttpResponseMessage 或抛出错误
【发布时间】:2012-07-17 13:23:44
【问题描述】:

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

使用其中任何一种都有哪些优点/缺点?在可扩展性和性能方面,哪一个比另一个更好?

【问题讨论】:

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


【解决方案1】:

如果有人好奇我的方向,我选择HttpResponseException 有几个原因:

  • 它使不熟悉 WebAPI 的人更容易阅读代码(大多数人都知道,当您抛出异常时,会出现问题)
  • 在我的测试中HttpResponseExceptions 返回更快,YMMV
  • 单元测试更容易(只需断言抛出异常)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-01
    • 2015-02-21
    • 1970-01-01
    • 2017-05-28
    • 2023-03-11
    • 1970-01-01
    • 2012-12-13
    • 2014-05-25
    相关资源
    最近更新 更多