MVC的Web API:为预检响应具有无效的HTTP状态码404级
问题描述:
我在两个服务器节点的服务时,我使用它有时它工作得很好,有时会错误MVC的Web API:为预检响应具有无效的HTTP状态码404级
XMLHttpRequest cannot load.. Response for preflight has invalid HTTP status code 404
我也跟着上计算器的答案,写了这个代码但它并没有解决问题
protected void Application_BeginRequest()
{
if (Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
的Web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
答
您可能需要使用此装饰[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
一个经营合同,例如:
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
和操作实现将是:
public void GetOptions()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
}
+0
谢谢你的帮助和努力。 你能告诉我把你的代码放在我的服务项目中吗? – Alex
+0
操作合同应放置在与客户端的调用遇到错误的服务合同相同的服务合同中,操作实现应放置在相应的服务类中。 –
的[AngularJS POST失败可能重复:为预检响应具有无效的HTTP状态代码404](https://stackoverflow.com/questions/33660712/angularjs-post-fails-response-for-preflight-has-invalid-http-status-code-404) – niksofteng