Web Api-不允许使用Catch 405方法 [英] Web Api - Catch 405 Method Not Allowed

查看:128
本文介绍了Web Api-不允许使用Catch 405方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,Web api应用程序将返回以下响应正文,表示"405-Method Not Allowed"错误.我正在尝试更改响应主体,但是我不知道如何使用委托处理程序,ApiControllerActionSelector或过滤器.有人可以帮助我在服务器端捕获405错误吗?

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'." }

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

注意:我的api控制器具有[RoutePrefix]值.

Note: My api controllers has [RoutePrefix] value.

推荐答案

您可以使用 DelegatingHandler 来捕获传出的响应并覆盖其行为.

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;
    }
}

在Global.asax中...

In Global.asax...

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

这篇关于Web Api-不允许使用Catch 405方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆