ASP.NET Web API、405 状态码和异常处理

Posted

技术标签:

【中文标题】ASP.NET Web API、405 状态码和异常处理【英文标题】:ASP.NET Web API, 405 status code and exception handling 【发布时间】:2012-09-21 11:08:41 【问题描述】:

有没有办法在 Web API 上捕获 405 并在发送错误动词时返回自定义消息?我使用 ExceptionFilterAttribute 捕获了 500 个。我想返回一个 JSON 或 XML 对象。

【问题讨论】:

您能举例说明如何发送错误的动词,例如:当客户端仍然发送 POST 时,您的 api 不支持 POST? 【参考方案1】:

HttpStatusCode.MethodNotAllowed 是你的朋友。

http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx

在您的过滤器中检查 Request.StatusCode。

【讨论】:

【参考方案2】:

您可以使用 System.Web 中的 customErrors 元素在 web.config 中设置它。

<customErrors defaultRedirect="url" mode="On">
   <error statusCode="statuscode" redirect="url"/>
</customErrors>

【讨论】:

以上是关于ASP.NET Web API、405 状态码和异常处理的主要内容,如果未能解决你的问题,请参考以下文章