ASP.NET Core Minimal API CORS
In this tutorial, you'll learn about ASP.NET Core Minimal API CORS. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Your minimal API serves a frontend from a different origin. Browsers block cross-origin requests with cryptic CORS errors.
Wrong
var app = builder.Build();
// No CORS configuration — blocks all cross-origin requests
app.MapGet("/api/data", () => Results.Ok(new { Data = "test" }));
Right
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.WithOrigins("https://myapp.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
app.UseCors("AllowFrontend");
app.MapGet("/api/data", () => Results.Ok(new { Data = "test" }));
Per-endpoint CORS:
app.MapGet("/api/public", () => Results.Ok("Public"))
.RequireCors(policy => policy.AllowAnyOrigin().AllowAnyMethod());
Prevention
- Add
AddCorsandUseCorsin the correct order (CORS before endpoints). - Restrict
WithOriginsto specific origins in production. - Use
AllowCredentials()with specific origins (notAllowAnyOrigin). - Use
AllowAnyHeader()andAllowAnyMethod()for most APIs. - Test with browser dev tools and OPTIONS preflight requests.
Common Mistakes with core minimal cors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world ASPNET code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
What is the correct middleware order for CORS?
`UseCors` must be called before `UseRouting` and `UseEndpoints` / `MapControllers`.For more guidance, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro