Search code examples
c#corsasp.net-core-webapiasp.net-core-6.0

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


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

Solution

  • The code that you posted seems to work fine. I pasted the code into a new .NET 6 project and the CORS headers are added in the response when a request like below is send from the browser.

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

    Results in the following response:
    enter image description here