ASP.NET 跨域配置

  • A+
所属分类:.NET技术
摘要

  The ‘Access-Control-Allow-Origin’ header is present on the requested resource   web.config配置信息


报错信息

  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 }             );         }     }