How to Enable CORS in ASP.NET Core 6.0 Web API

asp.net-core-6.0asp.net-core-webapic++cors

Configured CORS in my ASP.NET Core 6.0 Web API project. But the preflight request receives a http 405 error.

In other words HTTP OPTION is not allowed. Looks like cors is not enabled.

I've seen examples with config.EnableCors(); but there is no App_Start/WebApiConfig.cs in this project template.

What am I missing here?

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();

Best Answer

Add service builder.Services.AddCors and app add app.UseCors("corsapp");

replace builder.WithOrigins("*") with builder.WithOrigins("http://localhost:800", "https://misite.com");

check 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.UseHttpsRedirection();
        app.UseRouting();
        app.UseCors("corsapp");
        app.UseAuthorization();

        //app.UseCors(prodCorsPolicy);

    app.MapControllers();
    
    app.Run();
Related Question