预检的响应具有无效的HTTP状态代码400-ASPX [英] Response for preflight has invalid HTTP status code 400 - aspx
问题描述
我正在使用Visual Studio 2015编写服务器和客户端. 在Chrome和FireFox中会出现以下问题,但在资源管理器中可以完美运行. 我正在使用AJAX到我的服务器上进行Rest发帖,即AJAX代码:
I am writing both server and client using visual studio 2015. The following problem occurs in Chrome and FireFox, but works perfect in Explorer. I am doing a Rest post call using AJAX to my server, the AJAX code:
function CheckIntegrityExecution() {
var request = ...
var reqJson = JSON.stringify(request);
$.ajax({
type: "POST",
url: "http://localhost:55857/api/post/flow",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: reqJson,
success: function (jsonData) {
...
},
error: function () {
alert("error");
}
});
}
最初我遇到405错误,并且通过添加
Initially I was getting 405 error, and this was fixed with adding
var cors = new EnableCorsAttribute("http://localhost:55857", "*", "*");
config.EnableCors(cors);
到Global.asax中的Register函数:
To the Register function in Global.asax:
public static void Register(HttpConfiguration config)
现在出现以下错误:
XMLHttpRequest cannot load http://localhost:55857/api/post/flow. Response for preflight has invalid HTTP status code 400
我服务器中的方法签名是
The method signature in my server is
[Route("api/post/flow")]
public HttpResponseMessage PostCommand([FromBody] dynamic value)
我在WebApi的Web.config中拥有这些配置.
And I have these configuration in my Web.config in the WebApi.
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="OPTIONS, TRACE, GET, HEAD, POST, PUT" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Authorization, Accept, X-Requested-With" />
</customHeaders>
我注意到,如果我删除
contentType: "application/json; charset=utf-8",
在Ajax请求中,我可以工作,但不会在服务器中获取数据.
from the Ajax request I will work, but I will not get the data in my server.
我不知道该怎么办,尝试了一切.
I have no ideas what to do, tried everything.
推荐答案
解决方案是将以下内容添加到Global.asax文件中
The solution was to add the following to the Global.asax file
protected void Application_BeginRequest()
{
var context = HttpContext.Current;
var response = context.Response;
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.End();
}
}
这篇关于预检的响应具有无效的HTTP状态代码400-ASPX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!