Web Api - Catch 405 Method Not Allowed

2019-07-21 10:34发布

问题:

As of now, the Web api application returns the below response body for 405 - Method Not Allowed error. I am trying to change the response body, but I don't know how the delegating handler, ApiControllerActionSelector or filter can be used. Can anyone help me on catching the 405 error in server side?

{ message: "The requested resource does not support http method 'GET'." }

Note: My api controllers has [RoutePrefix] value.

回答1:

You could use a DelegatingHandler to catch the outgoing response and override its behaviour like this.

public class MethodNotAllowedDelegatingHandler : DelegatingHandler
{
    async protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        if (response.StatusCode == HttpStatusCode.MethodNotAllowed)
        {
            // adjust your response here as needed...
        }
        return response;
    }
}

In Global.asax...

config.MessageHandlers.Add(new MethodNotAllowedDelegatingHandler());