的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);
}
}
現在你只需要註冊您的DelegatingHandler
在Global.asax
:
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.MessageHandlers.Add(new XHttpMethodDelegatingHandler());
...
}
這應該是訣竅。
你是如何在你的控制器中定義你的方法的?在你的問題中顯示這將有助於提供答案。你在方法(s)上使用了屬性[HttpPut]嗎? –
我的確做到了 - [HttpPut] – nickthompson
其實,我意識到它是由X-HTTP-Method頭引起的。如果我使用WebRequest並將我的「Method」設置爲「PUT」,則它工作正常。所以現在我更困惑了! – nickthompson