How do you handle CORS in ASP.NET Core?
4 minintermediateASP.NET-CoreCORSsecurity
Quick Answer
CORS (Cross-Origin Resource Sharing) controls which browser origins may call your API. In ASP.NET Core you register policies with `AddCors`, then enable them with `UseCors` (placed before auth/endpoints) and optionally apply named policies per controller/endpoint via `[EnableCors]`. Configure allowed origins, headers, methods, and credentials explicitly — avoid `AllowAnyOrigin` combined with credentials.
Detailed Answer
CORS (Cross-Origin Resource Sharing) allows you to control which domains can access your API.
Method 1: Named Policy (Recommended)
// Program.cs
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
{
policy.WithOrigins("https://example.com", "https://app.example.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Must be called before UseAuthorization
app.UseCors("AllowSpecificOrigin");
Method 2: Apply to Specific Controllers
[EnableCors("AllowSpecificOrigin")]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Products");
[DisableCors] // Disable CORS for specific action
[HttpPost]
public IActionResult Post() => Ok();
}
Method 3: Apply to Specific Actions
[HttpGet]
[EnableCors("AllowAll")]
public IActionResult GetPublicData() => Ok("Public data");
Common CORS Configurations:
// Development - Allow all
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
// Production - Specific origins with credentials
policy.WithOrigins("https://myapp.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
// Specific methods and headers
policy.WithOrigins("https://myapp.com")
.WithMethods("GET", "POST")
.WithHeaders("Content-Type", "Authorization");