How do you apply different CORS policies to different endpoints or controllers within the same application?
Short answer
Register multiple named policies with AddCors, then apply a specific one to individual controllers or actions using [EnableCors("PolicyName")], overriding whatever the default/global policy might be -- and use [DisableCors] to explicitly opt an endpoint out of CORS entirely…
Advertisement
AModel answer
Register multiple named policies with AddCors, then apply a specific one to individual controllers or actions using [EnableCors("PolicyName")], overriding whatever the default/global policy might be -- and use [DisableCors] to explicitly opt an endpoint out of CORS entirely (blocking all cross-origin access to that specific endpoint) 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 { }
[EnableCors("AdminApi")]
public class AdminController : ControllerBase { }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 per controller.
Likely follow-ups
- What happens if both a global UseCors policy and an [EnableCors] attribute are present?
- How would [DisableCors] interact with a permissive global default policy?
Related topics