.netcore cors
配置跨域是后端职责所在
核心代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// 从 appsetting 获取跨域列表
var hostList = configuration.GetSection("Cors").GetChildren().Select(w => w.Value).ToArray();
services.AddCors(setupAction =>
{
// 配置跨域规则
setupAction.AddPolicy("cors", setupAction =>
{
//setupAction.AllowAnyOrigin();
setupAction.AllowAnyHeader();
setupAction.AllowAnyMethod();
setupAction.AllowCredentials().WithOrigins(hostList);
});
});
// 使用跨域中间件
app.UseCors("cors");辅助代码
- appsetting.json
1
2
3
4
5
6
7
8
9
10
11
12{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Cors": [
"http://localhost:5000",
"http://192.168.52.21:5000"
]
} - configuration, services, app
1
2
3
4
5
6
7
8
9
10
11
12
13public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
var app = builder.Build();
app.Run();
}
}
- appsetting.json