Skip to content

ASP.NET Core Minimal API CORS

DodaTech Updated 2026-06-24 1 min read

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" }));
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 AddCors and UseCors in the correct order (CORS before endpoints).
  • Restrict WithOrigins to specific origins in production.
  • Use AllowCredentials() with specific origins (not AllowAnyOrigin).
  • Use AllowAnyHeader() and AllowAnyMethod() for most APIs.
  • Test with browser dev tools and OPTIONS preflight requests.

Common Mistakes with core minimal cors

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [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`.
Can I use multiple CORS policies?

Yes. Define multiple named policies and apply them with RequireCors("PolicyName").

Does CORS affect server-side requests?

No. CORS is enforced by browsers only. Server-to-server requests are not affected.

For more guidance, visit DodaTech.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro