zoukankan      html  css  js  c++  java
  • 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 }
                );
            }
        }

    文件位置:

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

  • 相关阅读:
    hdu2243 考研路茫茫——单词情结【AC自动机】【矩阵快速幂】
    poj3376 Finding Palindromes【exKMP】【Trie】
    hdu4763 Theme Section【next数组应用】
    hdu2609 How many【最小表示法】【Hash】
    hdu3374 String Problem【最小表示法】【exKMP】
    poj2728 Desert King【最优比率生成树】【Prim】【0/1分数规划】
    python装饰器
    python面试题
    salt教程1-理解saltstack
    redis慢查询日志
  • 原文地址:https://www.cnblogs.com/dawenyang/p/10233743.html
Copyright © 2011-2022 走看看