ASP.NET 跨域配置

报错信息

  The 'Access-Control-Allow-Origin' header is present on the requested resource

解决方案

  web.config配置信息

  "Replace">
    "cors_allowOrigins" value="http://localhost:8002,http://192.168.0.1:8002" />
  

  不加上下面的配置项,跨域就不会生效,不知道为啥。


    
      
        "4294967295">
      
    
    
      "WebDAVModule" />
    
    
      "WebDAV" />
      "ExtensionlessUrlHandler-Integrated-4.0" />
      "OPTIONSVerbHandler" />
      "TRACEVerbHandler" />
      "ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    
  

  对应代码,初始化跨域配置  

   public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //异常捕捉
            config.Filters.Add(new ApiErrorHandleAttribute());

            // Web API 配置和服务
            var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"];
            var globalCors = new EnableCorsAttribute(allowOrigins, "*", "*")
            {
                SupportsCredentials = true
            };
            config.EnableCors(globalCors);
            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

补充 

如果想设置允许所有域名,那么只需要设置  SupportsCredentials = falseallowOrigins = "*",即可。

你可能感兴趣的:(ASP.NET 跨域配置)