AddCors registers Cross-Origin Resource Sharing services so an ASP.NET Core API can define which cross-origin browser requests it accepts. Add it to the API being accessed, not the application making the request; enable it only when a cross-origin requirement exists. section 29.3.2
A working CORS setup combines four parts:
- Call AddCors() and define at least one named policy. section 29.3.2
- Configure allowed origins, methods, headers, and credentials behavior through the policy builder. section 29.3.4
- Add CORS middleware after routing so it knows the selected endpoint. section 29.3.3
- Apply one default policy or select policies with RequireCors or EnableCors metadata; avoid combining default and endpoint policies unnecessarily. section 29.3.2 section 29.3.3
Allow one frontend origin
var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(options => { options.AddPolicy("AllowShoppingApp", policy => policy.WithOrigins("http://shopping.com") .AllowAnyMethod()); }); var app = builder.Build(); app.UseRouting(); app.UseCors("AllowShoppingApp"); app.MapGet("/api/products", () => new string[] { }); app.Run(); WithOrigins values must not include a trailing slash, or the origin will not match. section 29.3.2
Table 29.1 The methods available for configuring a CORS policy and their effect on the policy (view table figure)
Use the policy-options table to compare origin, method, header, and exposed-header restrictions before widening access. section 29.3.4
