Fix CORS Error in ASP.NET Core
Updated April 2026
Reading this article? Verify your fix in real-time. Test your ASP.NET CORS config live → CORSFixer
ASP.NET Core does not allow cross-origin requests by default. Register a CORS policy in Program.cs with builder.Services.AddCors() and apply it with app.UseCors().
Browser Console
Access to fetch at 'https://api.yourapp.com/api/products' from origin 'https://yourapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Program.cs — .NET 6+ minimal hosting
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{ options.AddPolicy("AllowFrontend", policy => { policy.WithOrigins("https://yourapp.com") .AllowAnyMethod() .AllowAnyHeader(); });
});
builder.Services.AddControllers();
var app = builder.Build();
// UseCors MUST come before UseAuthorization and MapControllers
app.UseCors("AllowFrontend");
app.UseAuthorization();
app.MapControllers();
app.Run();
With credentials (cookies / Authorization)
builder.Services.AddCors(options =>
{ options.AddPolicy("AllowFrontend", policy => { policy.WithOrigins("https://yourapp.com") // must be explicit .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); // enables credentials });
});
Multiple origins
policy.WithOrigins( "https://yourapp.com", "https://staging.yourapp.com", "http://localhost:3000" // development only )
Per-controller or per-action
// Apply named policy to a controller
[EnableCors("AllowFrontend")]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase { }
// Disable CORS on a specific action
[DisableCors]
[HttpGet("internal")]
public IActionResult InternalEndpoint() { }
Minimal API endpoints
app.MapGet("/api/data", () => Results.Ok(new { status = "ok" })) .RequireCors("AllowFrontend");
Common mistake — wrong middleware order
// WRONG — UseCors after UseAuthorization
app.UseAuthorization();
app.UseCors("AllowFrontend"); // too late
// CORRECT — UseCors before UseAuthorization
app.UseCors("AllowFrontend");
app.UseAuthorization(); Test your ASP.NET CORS config live → CORSFixer