JavaScript跨域访问

通过fetch访问后台C# Restful服务的时候,如果需要跨域,后台服务要设置支持CORS,否则会报错。

如果站点通过web服务器发布,会报如下错误:
Access to fetch at 'http://192.168.100.2:8080/Services/someAddress' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
如果是通过本地文件系统直接访问,没有把文件放到web服务器上,错误如下
Access to fetch at 'http://192.168.100.2:8080/Services/someAddress' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
可以通过两种方式设置C# Restful WCF Services支持CORS.

1.修改web.config文件

在congfiguration中增加下面的节点,在Configuration里增加Access-Control-Allow-Origin等设置。

<?xml version="1.0"?>
<configuration>  
  <system.serviceModel>         
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="AXServices.MobileTransfer">
        <endpoint address="" binding="webHttpBinding" contract="AXServices.MobileTransfer" behaviorConfiguration="web"/>
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

不过这种设置对于直接通过文件系统访问的时候不起作用,尝试将Access-Control-Allow-Origin的节点设置成null也没作用,不知道哪里还需要设置,暂时没找到设置的方法,或者这个方法不支持从本地文件发起的访问。
通过web服务器的URL访问可以正常使用。
2.增加Global.asax和Global.asax.cs文件

在Global.asax.cs增加如下代码

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

这种方法无论 通过web服务器还是文件访问都可以,将两个文件放到Services目录。

上一篇:django解决跨域问题


下一篇:Spring Boot - CORS支持