項目前后端分離,前端請求接口例如使用axios發送請求時瀏覽器會提示跨域錯誤,需要后端配置允許接口跨域
配置步驟:
1、通過NuGet安裝Microsoft.AspNetCore.Cors.dll類庫
2、在Startup.cs中的ConfigureServices方法加入以下配置
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分鍾內再次請求時,將不需要驗證跨域 }); });
3、在Startup.cs中的Configure方法加入以下配置
app.UseCors("CorsPolicy");
注意:必須要加在app.UseMvc();前面
4、在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()指定域名