我正在使用 Application_Error() 事件来获取 Web API 中的所有 HTTP 异常。此事件返回所有 HTTP 代码,例如“404”、“500”,并使用“Server.TransferRequest()”将请求传输到我的“错误 Controller ”以显示自定义错误。但如果出现 HTTP 错误“405”(“请求的资源不支持 HTTP 方法“GET/POST/PUT/DELETE”),Application_Error() 不会触发。我想在出现“405”时显示我自己的自定义错误实现这一点的一种方法可以是这样的:在 API 中为所有 Controller 公开 (GET,POST,PUT,DELETE) 方法,并从这些方法中返回我自己的自定义错误。但这不是实现该目的的好方法。有人可以指导我一种干净的方法来做到这一点吗? 任何帮助将不胜感激。
最佳答案
我知道有点晚了,但是你想要的可以通过 MessageHandlers 实现:
http://www.asp.net/web-api/overview/advanced/http-message-handlers
您必须实现一个DelegatingHandler
public class MethodNotAllowedHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == System.Net.HttpStatusCode.MethodNotAllowed)
{
//do your handling here
//maybe return a new HttpResponseMessage
}
return response;
}
}
然后将其添加到您的HttpConfiguration
config.MessageHandlers.Add(new MethodNotAllowedHandler());
关于asp.net-mvc - 使用 application_error() 事件处理 Web api 中的 HTTP "405"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27186730/