繁体   English   中英

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

[英]ASP.NET Web API return HttpResponseMessage or throw error

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

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

如果有人好奇我去了哪个方向,我会使用HttpResponseException ,原因有以下几点:

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

暂无
暂无

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

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