webapi 跨域问题

参考:http://www.cnblogs.com/chenxizhang/p/3821703.html

错误信息:Access to XMLHttpRequest at http://xxx.xxx from origin 'http://localhost:8002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request

方案一

给自己做个笔记

 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "origin,x-requested-with,content-type");
 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

web.config中添加这段代码

<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

 方案二

  web.config增加配置项

 <appSettings>
    <!--跨域设置-->
    <add key="cors_allowOrigins" value="http://localhost:8002,http://localhost:9536" />
  </appSettings>

  WebApiConfig.cs文件增加配置代码

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // 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 }
            );
        }
    }

文件位置:

 

 代码依赖引用,首先安装图片中引用

 

posted @ 2019-01-07 15:57  大稳·杨  阅读(1914)  评论(1编辑  收藏  举报