.NETCore设置跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
policy =>
{
policy.WithOrigins("http://example.com", "http://www.contoso.com")
.AllowAnyMethod()
.AllowAnyHeader();
});
});

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

// 在静态文件后调用
app.UseCors();

app.UseAuthorization();

app.MapControllers();

app.Run();

参考:

在 ASP.NET Core 中启用跨源请求 (CORS) | Microsoft Learn