ASP.NET Core cookbook · Beginner
Configure CORS for a browser front end
The SPA on another origin can't call the API, and someone suggests allowing every origin.
Approach
Define a named policy listing exact origins from configuration, the methods and headers you need, and credentials only if you use cookies. Apply it to the API endpoints.
Solution
var builder = WebApplication.CreateBuilder(args);
var origins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>() ?? ["https://app.example.com"];
builder.Services.AddCors(options => options.AddPolicy("spa", policy => policy
.WithOrigins(origins)
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Content-Type", "Authorization")
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromHours(1))));
var app = builder.Build();
app.UseCors();
app.MapGroup("/api").RequireCors("spa").MapGet("/me", () => new { name = "Ana" });
app.Run();
Pitfalls
AllowAnyOrigin()with credentials (not allowed) orSetIsOriginAllowed(_ => true)with credentials (dangerous).- Thinking CORS protects the API; it only controls which browser pages can read responses. Keep authentication.
- Missing
UseCors()or placing it after endpoints that need it.
Variations
- Serve the SPA and API from the same origin (reverse proxy) to avoid CORS entirely.
- Use
.WithExposedHeaders("ETag", "Location")when the front end needs to read those headers.
Further reading: Enable CORS
Reference: https://learn.microsoft.com/en-us/aspnet/core/security/cors
More ASP.NET Core recipes
- Accept file uploads with size and type limits
- Add OpenTelemetry traces and metrics
- Apply EF Core migrations safely during deployment
- Bind and validate options at startup
- Cache responses with output caching and evict by tag
- Call external APIs with typed HttpClients and resilience
- Expose liveness and readiness health checks
- Generate OpenAPI documents with Microsoft.AspNetCore.OpenApi