zoukankan      html  css  js  c++  java
  • ASP.NET 跨域配置

    报错信息

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

    解决方案

      web.config配置信息

      <appSettings xdt:Transform="Replace">
        <add key="cors_allowOrigins" value="http://localhost:8002,http://192.168.0.1:8002" />
      </appSettings>

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

    <system.webServer>
        <security>
          <requestFiltering>
            <requestLimits maxAllowedContentLength="4294967295"></requestLimits>
          </requestFiltering>
        </security>
        <modules>
          <remove name="WebDAVModule" />
        </modules>
        <handlers>
          <remove name="WebDAV" />
          <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>

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

       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 = "*",即可。

  • 相关阅读:
    oracle中pro*c的学习
    影响因子最大的国外计算机科学期刊50种
    eclipse3.6安装subversive插件
    WebLogic、WebSphere、JBOSS、Tomcat之间的区别
    hibernate.hbm.xml详解
    DotSpatial
    FLARtoolkit技巧:使用彩色marker
    全新体验 腾讯正式发布Sliverlight QQ
    ARToolKit技术视频欣赏
    写给未来的妻子你
  • 原文地址:https://www.cnblogs.com/dawenyang/p/13472533.html
Copyright © 2011-2022 走看看