ASP.Net Web API - 远程服务器返回错误:(405)方法不允许

nic*_*son 0 asp.net-mvc-4 asp.net-web-api

我正在使用新的MVC4 ASP.Net Web API系统.

我在使用WebClient的测试项目中调用我的API.如果我使用GET或POST,它可以正常工作.如果我使用其他任何东西,我会得到Method Not Allowed.我实际上是通过注入以下标题来"伪造"该方法.我这样做是因为我的最终用户也必须这样做,因为一些防火墙的限制.

我通过IIS调用URL(即不是cassini) - 例如http:// localhost/MyAPI/api/Test

wc.Headers.Add("X-HTTP-Method", "PUT");
Run Code Online (Sandbox Code Playgroud)

我尝试在IIS中调整脚本映射,但由于没有扩展,我不知道我要调整的是什么!

有任何想法吗?关心尼克

tpe*_*zek 7

X-HTTP-Method(或X-HTTP-Method-Override)头不受Web API支持开箱即用.您将需要创建一个自定义DelegatingHandler(下面的实现假定您使用POST方法发出请求):

public class XHttpMethodDelegatingHandler : DelegatingHandler
{
    private static readonly string[] _allowedHttpMethods = { "PUT", "DELETE" };
    private static readonly string _httpMethodHeader = "X-HTTP-Method";

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Method == HttpMethod.Post && request.Headers.Contains(_httpMethodHeader))
        {
            string httpMethod = request.Headers.GetValues(_httpMethodHeader).FirstOrDefault();
            if (_allowedHttpMethods.Contains(httpMethod, StringComparer.InvariantCultureIgnoreCase))
            request.Method = new HttpMethod(httpMethod);
        }
        return base.SendAsync(request, cancellationToken);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你只需要注册你DelegatingHandlerGlobal.asax:

protected void Application_Start(object sender, EventArgs e)
{
    GlobalConfiguration.Configuration.MessageHandlers.Add(new XHttpMethodDelegatingHandler());
    ...
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题.