Advertisement
Intermediate .NET, CORS & Cross-Origin Resource Sharing

How do you configure a CORS policy in ASP.NET Core to allow requests from specific origins?

Short answer

Register a named CORS policy via AddCors specifying allowed origins, methods, and headers, then apply it either globally with UseCors(policyName) in the middleware pipeline or per-endpoint/controller with the [EnableCors] attribute -- the policy must be registered before…

Save .NET mock interview
Advertisement
AModel answer
Register a named CORS policy via AddCors specifying allowed origins, methods, and headers, then apply it either globally with UseCors(policyName) in the middleware pipeline or per-endpoint/controller with the [EnableCors] attribute -- the policy must be registered before UseAuthorization and typically right after UseRouting in the pipeline order.
builder.Services.AddCors(options => {
    options.AddPolicy("AllowFrontend", policy => {
        policy.WithOrigins("https://app.mycompany.com")
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

app.UseCors("AllowFrontend");  // after UseRouting, before UseAuthorization
Real-world example
A public API explicitly whitelists only its known frontend origin (https://app.mycompany.com) rather than using a wildcard, ensuring only that specific frontend can make cross-origin requests with credentials.
Likely follow-ups
  • Why must UseCors be positioned specifically between UseRouting and UseAuthorization?
  • How do you apply different CORS policies to different controllers?
Related topics