asp.net core api 跨域配置
项目前后端分离,前端请求接口例如使用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()指定域名