第一種在Web.config中<system.webServer>節點中配置(不支持多個域名跨域)html
1 <httpProtocol> 2 <customHeaders> 3 <add name="Access-Control-Allow-Origin" value="http://localhost:31551" /> 4 <add name="Access-Control-Allow-Headers" value="*" /> 5 <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /> 6 </customHeaders> 7 </httpProtocol>
第二種方式,在項目中用NuGet安裝microsoft.aspnet.webapi.cors(支持多個域名跨域)web
若是遇到 System.FieldAccessException: 方法「System.Web.Http.GlobalConfiguration..cctor()」嘗試訪問字段「System.Web.Http.GlobalConfiguration.CS$<>9__CachedAnonymousMethodDelegate2」失敗。api
這個問題,我這邊 是由於 Microsoft.AspNet.WebApi 2 沒有安裝,安裝以後就沒問題了跨域
1.而後在App_Start文件夾下面的WebApiConfig.cs文件夾配置跨域app
2.也能夠在配置文件中設置,而後讀取配置文件cors
在appSettings節點中配置spa
1 <add key="cors_allowOrigins" value="http://localhost:31551,http://localhost:6449"/> 2 <add key="cors_allowHeaders" value="*"/> 3 <add key="cors_allowMethods" value="*"/>
而後在App_Start文件夾下面的WebApiConfig.cs文件夾配置跨域3d
1 public static void Register(HttpConfiguration config) 2 { 3 //跨域配置 4 //config.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:31551,http://localhost:6449", "*", "*")); 5 6 var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"]; 7 var allowHeaders = ConfigurationManager.AppSettings["cors_allowHeaders"]; 8 var allowMethods = ConfigurationManager.AppSettings["cors_allowMethods"]; 9 var globalCors = new System.Web.Http.Cors.EnableCorsAttribute(allowOrigins, allowHeaders, allowMethods); 10 config.EnableCors(globalCors); 11 12 config.Routes.MapHttpRoute( 13 name: "DefaultApi", 14 routeTemplate: "api/{controller}/{action}/{id}", 15 defaults: new { id = RouteParameter.Optional } 16 ); 17 }
3.若是你只想對某一些api作跨域,能夠直接在API的類上面使用特性標註便可。code
先在App_Start文件夾下面的WebApiConfig.cs啓用Corshtm
而後在接口前面加上標註就好了
1 [System.Web.Http.Cors.EnableCors(origins: "http://localhost:31551", headers: "*", methods: "GET,POST,PUT,DELETE")] 2 public class ChargingController : ApiController 3 { 4 /// <summary> 5 /// 獲得全部數據 6 /// </summary> 7 /// <returns>返回數據</returns> 8 [HttpGet] 9 public string GetAllChargingData() 10 { 11 return "Success"; 12 } 13 }