UseCors adds CORS middleware to an ASP.NET Core application. With a policy name, it applies that policy as the application's default CORS policy; without one, endpoint-specific policies can select the rules. section 29.3.2 section 29.3.3
Apply a policy globally
Register an AllowShoppingApp policy for http://shopping.com, then place app.UseCors("AllowShoppingApp") after app.UseRouting(). The middleware permits matching browser requests and adds the headers needed for preflight responses; other origins remain blocked.
UseCors requires a deliberate scope and pipeline position:
- Place it after UseRouting() so the middleware knows the selected endpoint and can generate correct preflight responses. section 29.3.2 section 29.3.3
- Choose a global default for an application-wide rule, or call UseCors() without a default policy when endpoints select policies with RequireCors or EnableCors. section 29.3.3
- Avoid combining a default policy with endpoint policies unless the combined behavior is intentional, because both policies are applied. section 29.3.3
- Match origins exactly in WithOrigins(), including no trailing slash, or cross-origin requests will fail to match. section 29.3.2
Listing 29.4 Applying a CORS policy to minimal API endpoints
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options => { /* Config not shown*/});
var app = builder.Build();
app.UseCors(); #1
app.MapGet("/api/products", () => new string[] {})
.RequireCors("AllowShoppingApp"); #2
app.MapGet("/api/products",
[EnableCors("AllowShoppingApp")] () => new { }); #3
app.MapGroup("/api/categories")
.RequireCors("AllowAnyOrigin"); #4
app.MapDelete("/api/products",
[DisableCors] () => Results.NoContent()); #5
app.Run();
#1 Adds the CorsMiddleware without configuring a default policy
#2 Applies the AllowShoppingApp CORS policy to the endpoint
#3 You can apply attributes to the lamba or handler method, as well as to MVC action methods.
#4 You can apply CORS policies to whole route groups.
#5 The DisableCors attribute disables CORS for the endpoint completely.
Compare middleware without a default policy with endpoint, route-group, and controller-level CORS selection. section 29.3.3
