🌐 Blocked by CORS? Configure It.
Browser blocks API calls from different origins. CORS configuration allows specific domains. Security by default, flexibility when needed.
📝 Basic CORS
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Allow any origin (development only!)
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
app.UseCors("AllowAll");
app.Run();
🎯 Production CORS (Specific Origins)
builder.Services.AddCors(options =>
{
options.AddPolicy("Production", policy =>
{
policy.WithOrigins(
"https://myapp.com",
"https://admin.myapp.com"
)
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Authorization", "Content-Type")
.AllowCredentials(); // Allow cookies/auth headers
});
});
// Multiple policies
options.AddPolicy("PublicAPI", policy =>
{
policy.WithOrigins("*")
.WithMethods("GET")
.WithHeaders("*");
});
// Use specific policy per endpoint
app.MapGet("/api/public", handler).RequireCors("PublicAPI");
💡 Environment-Specific
- Development: AllowAnyOrigin() for easy testing
- Production: WithOrigins() with specific domains
- Use configuration for origins list (appsettings.json)
- Never use AllowAnyOrigin with AllowCredentials (browser blocks)
“SPA on different domain couldn’t call API. Added CORS policy. Now SPA works. Security preserved. CORS is essential for modern web apps.”
