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

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

Leave a Comment

tech