项目前后端分离,前端请求接口例如使用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分钟内再次请求时,将不需要验证跨域
}); });
3、在Startup.cs中的Configure方法加入以下配置
app.UseCors("CorsPolicy");
注意:必须要加在app.UseMvc();前面
4、在appsettings.json配置可以跨域的域名:
"CorsOrigins": [ "http://www.testseparateapi.com:8080", "http://localhost:8080" ]
ConfigHelper读取appsettings.json工具类代码:
/// <summary>
/// appsettings.json配置文件帮助类
/// </summary>
public class ConfigHelper
{
static ConfigHelper()
{
Microsoft.Extensions.Configuration.IConfiguration config = AutofacHelper.GetService<Microsoft.Extensions.Configuration.IConfiguration>();
if (config == null)
{
var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json"); config = builder.Build();
} _config = config;
} private static Microsoft.Extensions.Configuration.IConfiguration _config { get; } #region 从appsettings.json获取key的值
/// <summary>
/// 从appsettings.json获取key的值
///
/// 列如:appsettings.json的格式如下
///
/// {
///
/// "Logging": {
/// "LogLevel": {
/// "Default": "Warning"
/// }
///},
/// "AllowedHosts": "*",
/// "RabbitMQ": {
/// "HostName": "111",
/// "UserName": "11",
/// "Password": "11",
/// "ReTryCount": "5"
/// }
///}
///
/// 取RabbitMQ下的HostName的值,则参数key为 RabbitMQ:HostName
///
/// </summary>
/// <param name="key">key</param>
/// <returns></returns>
public static string GetValue(string key)
{
var rr = _config.GetSection(key).GetChildren(); return _config[key];
}
#endregion #region appsettings.json 子节点转实体
/// <summary>
/// appsettings.json 子节点转实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">节点名称</param>
/// <returns></returns>
public static T GetSectionModel<T>(string key) where T : new()
{
var model = new T();
_config.GetSection(key).Bind(model);
return model;
} #endregion /// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="nameOfCon">连接字符串名</param>
/// <returns></returns>
public static string GetConnectionString(string nameOfCon)
{
return _config.GetConnectionString(nameOfCon);
}
}
配置允许所有域名通过跨域,builder.AllowAnyOrigin(),客户端请求的时候携带cookie或者其他参数的时候出现以下错误,必须通过builder.WithOrigins()指定域名