1

我正在使用 Application_Error() 事件来获取 Web API 中的所有 HTTP 异常。此事件返回所有 HTTP 代码,例如“404”、“500”,并使用“Server.TransferRequest()”将请求传输到我的“错误控制器”以显示自定义错误。但是在 HTTP 错误“405”(“请求的资源不支持 HTTP 方法 'GET/POST/PUT/DELETE')的情况下,Application_Error() 不会触发。我想在“405”的情况下显示我自己的自定义错误实现这一点的一种方法是:在 API 中为所有控制器公开 (GET,POST,PUT,DELETE) 方法,并从这些方法中返回我自己的自定义错误。但这不是实现目的的好方法。谁能指导我一个干净的方法来做到这一点?任何帮助将不胜感激。

4

1 回答 1

2

我知道这有点晚了,但是使用 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());
于 2016-08-23T22:15:37.947 回答