Web API 不支持开箱即用的X-HTTP-Method
(or ) 标头。X-HTTP-Method-Override
您将需要创建一个自定义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);
}
}
现在您只需要注册您的DelegatingHandler
in Global.asax
:
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.MessageHandlers.Add(new XHttpMethodDelegatingHandler());
...
}
这应该可以解决问题。