Internet Explorer中跨站点请求的访问控制

Ale*_*vić 9 javascript internet-explorer access-control cross-domain

我正在尝试从几个域进行AJAX调用到一个将处理请求的域.通过在处理服务器上设置标头,可以轻松在Firefox和Chrome中启用跨域:

header("Access-Control-Allow-Origin: *");
Run Code Online (Sandbox Code Playgroud)

但这无助于在Internet Explorer中启用它.当我尝试:

httpreq.send('');
Run Code Online (Sandbox Code Playgroud)

它会因错误访问被拒绝而停止.

如何在Internet Explorer中启用它?

Joh*_*eci 12

自从我第一次在IE7及更高版本中发布CORS解决方案以来,已经发生了很大的变化.首先,jQuery属性$ .support.cors默认为true,.NET frameworks 4.0及更高版本不再支持在3.5.1及更低版本中实现的CORS.使用ASP.NET 4.0编写Web服务时,我安装了Thinktecture.IdentityModel,它可以作为NuGet包使用.然后,在Global.asax文件的Application_Start方法中,添加:

void Application_Start(object sender, EventArgs e) 
{ 
    Thinktecture.IdentityModel.Http.Cors.IIS.UrlBasedCorsConfiguration.Configuration
        .ForResources("*")
        .ForOrigins("http://localhost:80, http://mydomain")
        .AllowAll()
        .AllowMethods("GET", "POST");
}
Run Code Online (Sandbox Code Playgroud)

现在在system.webServer中添加httpProtocol元素:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, X-Requested-With, X-File-Name" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
  </customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)

我的$ .ajax电话现在是:

$.ajax({
    url: serviceUrl, 
    data: JSON.stringify(postData),
    type: "POST",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: onSuccess,
    error: onError
});
Run Code Online (Sandbox Code Playgroud)


van*_*102 7

您是否尝试启用Access Data Source Cross Domains 在此输入图像描述

  • 这对于在 localhost:8080 上测试网站很有用 (2认同)

Dan*_*Dan 5

我不相信你可以直接在Internet Explorer中这样做.你有几个选择:

  • 在您控制的可以转发Ajax请求的服务器上设置代理转发脚本.确保它只转发到您需要的相应目的地,这样您就不会变成匿名中继.

  • 使用document.domain技巧.基本上你需要创建一组iframes,一个用于调用Ajax所需的每个服务器.在每个iframe设置document.domain属性域完全匹配,您需要将Ajax请求发送.至于如何填充必要的数据,请在设置之前使用DOM操作document.domain.请注意,此技巧要求目标服务器位于原始服务器的子域中.更多内容在本文中,附带示例.