🔐 CORS = API Security
Browsers block cross-origin requests. CORS configuration enables secure API access. Essential for modern APIs.
📝 CORS Setup
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add CORS policy
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("https://myapp.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
options.AddPolicy("AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// Use CORS
app.UseCors("AllowSpecificOrigin");
// Or with endpoints
app.UseCors();
app.MapControllers();
🎯 Advanced CORS
// Controller-level CORS
[ApiController]
[Route("api/[controller]")]
[EnableCors("AllowSpecificOrigin")]
public class UsersController : ControllerBase
{
// ...
}
// Action-level CORS
[HttpPost]
[EnableCors("AllowMultipleOrigins")]
public IActionResult Create(User user)
{
// ...
}
// Disable CORS
[DisableCors]
public IActionResult Internal()
{
// ...
}
// CORS with exposed headers
builder.Services.AddCors(options =>
{
options.AddPolicy("WithHeaders",
builder =>
{
builder.WithOrigins("https://myapp.com")
.WithMethods("GET", "POST", "PUT")
.WithHeaders("Content-Type", "X-Custom-Header")
.WithExposedHeaders("X-Total-Count", "X-Pagination")
.SetPreflightMaxAge(TimeSpan.FromMinutes(10));
});
});
// CORS Tips
- Don't use AllowAnyOrigin in production
- Use specific origins only
- Allow credentials carefully
- Use environment-specific config
- Test CORS with browser dev tools
💡 CORS Tips
- Don’t use AllowAnyOrigin in production
- Use specific origins only
- Allow credentials carefully
- Use environment-specific config
- Test CORS with browser dev tools
“CORS configuration secures APIs. Specific origins, methods, headers. Essential for API security.”




