CORS
suggest changeCross-Origin Resource Sharing (CORS) is a browser security specification that prevents client-side web applications (such as single-page applications built in React, Vue, or Blazor WebAssembly) from querying a backend API hosted on a different domain, protocol, or port unless the server explicitly grants permission via HTTP response headers.
In ASP.NET Core, CORS is managed via the built-in Microsoft.AspNetCore.Cors middleware.
Enabling CORS in Program.cs
Enabling CORS involves two steps: registering named or default policies in the dependency injection container, and adding the CORS middleware to the request processing pipeline.
var builder = WebApplication.CreateBuilder(args);
// Step 1: Register CORS services and define policies
builder.Services.AddCors(options =>
{
options.AddPolicy("FrontendPolicy", policy =>
{
policy.WithOrigins("https://app.example.com", "http://localhost:3000")
.WithMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.WithHeaders("Content-Type", "Authorization", "X-Requested-With")
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromHours(24));
});
// Optional open policy for public endpoints
options.AddPolicy("PublicApiPolicy", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
// Step 2: Apply CORS middleware
// IMPORTANT: UseCors must be placed between UseRouting and UseAuthorization
app.UseCors("FrontendPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Middleware Ordering Requirement
In ASP.NET Core, the order of middleware in Program.cs is critical. app.UseCors() must be called:
- After
app.UseRouting() - Before
app.UseAuthentication()andapp.UseAuthorization()
If placed after UseAuthorization(), preflight OPTIONS requests sent by browsers (which do not carry credentials) will be rejected with an HTTP 401 Unauthorized before CORS headers can be written.
Applying CORS Per Controller or Endpoint
Instead of applying a global policy with app.UseCors("PolicyName"), you can apply policies granularly:
In Controllers ([EnableCors])
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
[EnableCors("FrontendPolicy")] // Applied to all actions in this controller
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult GetOrders() => Ok(new[] { "Order 1", "Order 2" });
[HttpGet("public-stats")]
[EnableCors("PublicApiPolicy")] // Overrides with a different policy
public IActionResult GetPublicStats() => Ok(new { total = 1000 });
[HttpGet("internal")]
[DisableCors] // Explicitly disables CORS for this endpoint
public IActionResult GetInternalData() => Ok();
}
In Minimal APIs (RequireCors)
app.MapGet("/api/products", () => Results.Ok(new[] { "Product A", "Product B" }))
.RequireCors("FrontendPolicy");
Security Best Practices
- Never combine
AllowAnyOrigin()withAllowCredentials(): Browsers strictly reject responses whereAccess-Control-Allow-Origin: *accompaniesAccess-Control-Allow-Credentials: true. - Dynamic Origin Validation: To allow wildcard subdomains securely (e.g.
*.mycompany.com), useSetIsOriginAllowed:policy.SetIsOriginAllowed(origin => new Uri(origin).Host.EndsWith(".mycompany.com")) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); - Exposing Headers: If your client needs to read custom headers from the response (such as pagination headers), specify them with
.WithExposedHeaders("X-Total-Count").