在.NET 6中,AllowAnyOrigin()
方法对任意的源不再可用,要实现跨域,可以通过WithOrigins()
方法指定单个或多个允许跨域的地址,如下:
namespace WebApplication6
{
public class Program
{
public static void Main(string[] args)
{
var policyName = "AllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{
options.AddPolicy(name: policyName,
policyBuilder =>
{
policyBuilder
.WithOrigins("http://localhost:3000", "http://localhost:3001", "http://localhost:3002")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(policyName);
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
或者,你如果需要允许所有源,则可通过SetIsOriginAllowed()
方法配置允许所有源跨域,示例如下: