如何在 ASP.NET Core 6.0 Web API 项目中启用 cors?

How to enable cors in ASP.NET Core 6.0 Web API project?

在我的 ASP.NET Core 6.0 Web API 项目中配置了 CORS。但是预检请求收到 http 405 错误。

换句话说,HTTP OPTION 是不允许的。似乎没有启用 cors。

我看过 config.EnableCors(); 的示例,但此项目模板中没有 App_Start/WebApiConfig.cs

我在这里错过了什么?

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var devCorsPolicy = "devCorsPolicy";
builder.Services.AddCors(options =>
{
    options.AddPolicy(devCorsPolicy, builder => {
        //builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
        //builder.SetIsOriginAllowed(origin => true);
    });
});


var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseCors(devCorsPolicy);
}
else 
{
    app.UseHttpsRedirection();
    app.UseAuthorization();
    //app.UseCors(prodCorsPolicy);
}

app.MapControllers();

app.Run();

添加服务 builder.Services.AddCors 和应用程序添加 app.UseCors("corsapp");

builder.WithOrigins("*")替换为builder.WithOrigins("http://localhost:800", "https://misite.com");

检查documentation

     var builder = WebApplication.CreateBuilder(args);

    
    // Add services to the container.
    
    builder.Services.AddControllers();
    
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    //services cors
    builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
    {
        builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
    }));
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
        
    }
       //app cors
        app.UseCors("corsapp");
        app.UseHttpsRedirection();
        app.UseAuthorization();
        //app.UseCors(prodCorsPolicy);
    
    
    
    app.MapControllers();
    
    app.Run();

您发布的代码似乎工作正常。我将代码粘贴到一个新的 .NET 6 项目中,当从浏览器发送如下请求时,CORS headers 被添加到响应中。

fetch('http://localhost:7107/Weatherforecast').then(res => res.json()).then(e => console.log(e))

结果如下: