Web Api - Catch 405 Method Not Allowed

二次信任 提交于 2019-12-11 02:08:10

问题


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());


来源:https://stackoverflow.com/questions/24499096/web-api-catch-405-method-not-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!