我有一个 WebService (.asmx) 页面,其中包含我想要从另一个网页运行的许多功能。我想要使用 ajax 来调用函数的网页与 Web 服务来自不同的来源。当我尝试以下 ajax 调用时:
$.ajax({
type: "POST",
url: "http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList",
crossDomain: true,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'filterID': 0
}),
dataType: "json",
success: function (data)
{
data = JSON.parse(data.d);
console.log(data);
}
});
我收到以下错误:
XMLHttpRequest cannot load http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.
我可以使用在托管 Web 服务的同一台计算机上的浏览器上作为 url 提供的确切链接,并且一切都按预期运行。使用来自 internet explore 11 或 Edge 的 ajax 调用也可以正常工作,但是当从 google chrome 运行命令时,会出现上述错误。
仔细阅读,这似乎是我的网络服务未在其 CORS 响应数据包中添加正确字段的问题,因此 google chrome 设置会捕获它并引发错误。我尝试编写用于 Web API 的代码来启用 CORS(请参阅以下代码块)。
public static void Register(HttpConfiguration config)
{
//TODO: determine acceptable origins
var corsAttr = new EnableCorsAttribute("*", "*", "*"); //accept all origins, headers, and methods
config.EnableCors(corsAttr); //enable cross origin requests
}
这似乎不起作用,我无法使用 Web 服务而不是 Web API 找到此问题的文档。如何修复 Web 服务和/或 ajax 调用以正确启用 CORS?
编辑 将以下代码行添加到 Web 配置文件可修复 header 的 CORS 部分未添加的问题:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
但是,我仍然收到 404 错误。在托管 Web 服务的计算机上测试 ajax 调用,ajax 正常工作且符合预期。但是,当跨源运行它时,我收到 404 错误。
最佳答案
即使将自定义 header 添加到 Web 配置后,404 错误仍然存在。这最终是由于 header 仍然不完全正确或 ISAPI 使用 OPTIONS 动词拦截数据包并导致一些我从未弄清楚确切原因的问题。我的解决方案是删除对 Web 配置的更改,并使用以下代码添加全局 asax 文件:
<%@ Application Language="C#"%>
<script RunAt="server">
void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var response = context.Response;
// enable CORS
response.AddHeader("Access-Control-Allow-Origin", "*");
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();
}
}
</script>
这可以确保数据包具有正确的 header 。您必须删除我在问题中提到的 Web 配置部分,因为它会将它们添加两次,这也会导致 ajax 调用失败。
关于jquery - 如何使用 Web 服务和 jQuery Ajax 启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45826696/