The 'Access-Control-Allow-Origin' header is present on the requested resourceweb
web.config配置信息api
<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>
對應代碼,初始化跨域配置 app
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 = false,allowOrigins = "*",便可。cors