一、在api配置文件Startup中定义全局变量:
public readonly string anyAllowSpecificOrigins = "any";
二、在api的appsettings.json中添加配置信息(允许跨域访问的url):
"CorsPaths": {
"OriginOne": "http://localhost:5001",
"OriginOnes": "https://localhost:5001",
"OriginThree": "http://www.hrms.com:80/",
"OriginThrees": "https://www.hrms.com:80/"
}
三、NuGet包管理器,安装:Microsoft.AspNetCore.Mvc.Cors
四、在api配置文件Startup中ConfigureServices方法里配置跨域处理cors:
//配置跨域处理cors
services.AddCors(options =>
{
options.AddPolicy(anyAllowSpecificOrigins, corsbuilder =>
{
var corsPath = Configuration.GetSection("CorsPaths").GetChildren().Select(p=>p.Value).ToArray();
corsbuilder.WithOrigins(corsPath)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();//指定处理cookie
});
});
五、在api配置文件Startup中Configure方法里添加app.UseCors(anyAllowSpecificOrigins):
app.UseRouting();
app.UseCors(anyAllowSpecificOrigins);//支持跨域:允许特定来源的主机访问
app.UseHttpsRedirection();
app.UseAuthorization();
特别说明:此项必须在app.UseRouting()和app.UseAuthorization()之间,否则会报错。
五、在api配置文件Startup中Configure方法里app.UseEndpoints添加.RequireCors(anyAllowSpecificOrigins):
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(anyAllowSpecificOrigins);
});
至此,配置完毕。欢迎各位批评指正!