CORS middleware lets an ASP.NET Core API control which cross-origin browser requests are allowed. Configure CORS only when a separate-origin app needs API access, because browsers block these requests to reduce attack opportunities. section 29.3.2
Set up CORS in four steps:
- Register CORS services with AddCors(). section 29.3.2
- Define at least one named policy specifying allowed origins, headers, and HTTP methods. section 29.3.2
- Add UseCors() after routing so endpoint metadata is available when the middleware selects a policy. section 29.3.3
- Apply one policy globally or select policies per endpoint with RequireCors() or EnableCors metadata. section 29.3.2 section 29.3.3
Allow a separate shopping app
Register an AllowShoppingApp policy for http://shopping.com, permit the required HTTP methods, then call UseCors("AllowShoppingApp") before mapping the API endpoints. Do not add a trailing slash to the configured origin, or matching fails. 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 endpoint-level policy selection with a default policy, route-group configuration, and disabling CORS for a specific endpoint. section 29.3.3

