項目先後端分離,前端請求接口例如使用axios發送請求時瀏覽器會提示跨域錯誤,須要後端配置容許接口跨域前端
配置步驟:ios
一、經過NuGet安裝Microsoft.AspNetCore.Cors.dll類庫json
二、在Startup.cs中的ConfigureServices方法加入如下配置axios
services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { //builder.AllowAnyOrigin(); //客戶端不攜帶cookie時,能夠配置 builder.WithOrigins(ConfigHelper.GetSectionModel<List<string>>("CorsOrigins").ToArray()); //客戶端攜帶cookie、或者在請求報文定義其餘字段屬性時,必須指定域名 builder.AllowAnyHeader(); builder.AllowAnyMethod(); builder.AllowCredentials(); builder.SetPreflightMaxAge(TimeSpan.FromSeconds(60)); //若是接口已驗證過一次跨域,則在60分鐘內再次請求時,將不須要驗證跨域 }); });
三、在Startup.cs中的Configure方法加入如下配置後端
app.UseCors("CorsPolicy");
注意:必需要加在app.UseMvc();前面api
四、在appsettings.json配置能夠跨域的域名:跨域
"CorsOrigins": [ "http://www.testseparateapi.com:8080", "http://localhost:8080" ]
ConfigHelper讀取appsettings.json工具類代碼:
1 /// <summary> 2 /// appsettings.json配置文件幫助類 3 /// </summary> 4 public class ConfigHelper 5 { 6 static ConfigHelper() 7 { 8 Microsoft.Extensions.Configuration.IConfiguration config = AutofacHelper.GetService<Microsoft.Extensions.Configuration.IConfiguration>(); 9 if (config == null) 10 { 11 var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json"); 12 13 config = builder.Build(); 14 } 15 16 _config = config; 17 } 18 19 private static Microsoft.Extensions.Configuration.IConfiguration _config { get; } 20 21 #region 從appsettings.json獲取key的值 22 /// <summary> 23 /// 從appsettings.json獲取key的值 24 /// 25 /// 列如:appsettings.json的格式以下 26 /// 27 /// { 28 /// 29 /// "Logging": { 30 /// "LogLevel": { 31 /// "Default": "Warning" 32 /// } 33 ///}, 34 /// "AllowedHosts": "*", 35 /// "RabbitMQ": { 36 /// "HostName": "111", 37 /// "UserName": "11", 38 /// "Password": "11", 39 /// "ReTryCount": "5" 40 /// } 41 ///} 42 /// 43 /// 取RabbitMQ下的HostName的值,則參數key爲 RabbitMQ:HostName 44 /// 45 /// </summary> 46 /// <param name="key">key</param> 47 /// <returns></returns> 48 public static string GetValue(string key) 49 { 50 var rr = _config.GetSection(key).GetChildren(); 51 52 return _config[key]; 53 } 54 #endregion 55 56 #region appsettings.json 子節點轉實體 57 /// <summary> 58 /// appsettings.json 子節點轉實體 59 /// </summary> 60 /// <typeparam name="T"></typeparam> 61 /// <param name="key">節點名稱</param> 62 /// <returns></returns> 63 public static T GetSectionModel<T>(string key) where T : new() 64 { 65 var model = new T(); 66 _config.GetSection(key).Bind(model); 67 return model; 68 } 69 70 #endregion 71 72 /// <summary> 73 /// 獲取鏈接字符串 74 /// </summary> 75 /// <param name="nameOfCon">鏈接字符串名</param> 76 /// <returns></returns> 77 public static string GetConnectionString(string nameOfCon) 78 { 79 return _config.GetConnectionString(nameOfCon); 80 } 81 }
配置容許全部域名經過跨域,builder.AllowAnyOrigin(),客戶端請求的時候攜帶cookie或者其餘參數的時候出現如下錯誤,必須經過builder.WithOrigins()指定域名瀏覽器