16

来自http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

HttpResponseException

如果 Web API 控制器抛出异常会发生什么?默认情况下,大多数异常都会转换为状态代码为 500(内部服务器错误)的 HTTP 响应。

HttpResponseException 类型是一种特殊情况。此异常返回您在异常的构造函数中指定的任何 HTTP 状态代码。

除了它没有。Fiddler 向我展示了 500 的返回值。

但是, HttpException 似乎做了那篇文章所说的。

文档是错误的还是我遗漏了什么?

更新

在打字的时候,我有了一个想法。我尝试了两个控制器,一个 ApiController 和一个标准 MVC 控制器。

这两个异常根据抛出它们的控制器类型相互反向工作。

  • 使用 HttpResponseException 从 API 控制器返回正确的 HTTP 代码。
  • 使用 HttpException 从 MVC 控制器返回正确的 HTTP 代码。
4

1 回答 1

18

[Moved my update to an answer]

While typing that out, I had an idea. I tried both from two controllers, an ApiController and a standard MVC controller.

The two exception work in reverse to each other depending on the type of controller they're thrown from.

  • Use HttpResponseException to return a proper HTTP code from an API controller.
  • Use HttpException to return a proper HTTP code from an MVC controller.
于 2012-11-23T11:02:31.010 回答