How do you apply different CORS policies to different controllers or minimal API endpoint groups within the same application?
Short answer
Register multiple named policies via AddCors, then apply a specific one per controller/action using [EnableCors("PolicyName")] (overriding any default/global policy), or per minimal API endpoint/group using .RequireCors("PolicyName") -- use [DisableCors] to explicitly opt an…
Advertisement
AModel answer
Register multiple named policies via AddCors, then apply a specific one per controller/action using [EnableCors("PolicyName")] (overriding any default/global policy), or per minimal API endpoint/group using .RequireCors("PolicyName") -- use [DisableCors] to explicitly opt an endpoint out of CORS entirely regardless of the global configuration.
builder.Services.AddCors(options => {
options.AddPolicy("PublicApi", p => p.AllowAnyOrigin().WithMethods("GET"));
options.AddPolicy("AdminApi", p => p.WithOrigins("https://admin.mycompany.com").AllowCredentials());
});
[EnableCors("PublicApi")]
public class ProductsController : ControllerBase { }
app.MapGroup("/admin").RequireCors("AdminApi");Real-world example
A single API exposes both a fully public, read-only product catalog (permissive CORS for any origin) and a sensitive admin management interface (restricted to only the internal admin frontend's origin with credentials), using distinct named CORS policies.
Likely follow-ups
- What happens if both a global UseCors default policy and a per-endpoint policy are present?
- How does [DisableCors] interact with a permissive global default?
Related topics