A browser script may need to call an API hosted somewhere other than the page it runs on. Normally, the same-origin policy blocks that request unless the page and resource share a protocol, host, and port. Cross-Origin Resource Sharing (CORS) lets the server use HTTP headers to permit selected cross-origin requests. This matters when a browser client and a board-game API are hosted at different origins. section 3.1.1
In ASP.NET Core, set up CORS in three parts:
- Register CORS services with AddCors and define a default policy or a named policy. A policy specifies which origins, headers, and HTTP methods to allow. section 3.1.1
- Add UseCors to the request pipeline. UseCors() selects the default policy; UseCors("AnyOrigin") selects the named policy shown in the configuration examples. section 3.1.1
- When different endpoints need different rules, attach a named policy with RequireCors to a Minimal API endpoint or controller mapping; an EnableCors attribute is another shown option. section 3.1.1
builder.Services.AddCors(options => {
options.AddDefaultPolicy(cfg => {
cfg.WithOrigins(builder.Configuration["AllowedOrigins"]);
cfg.AllowAnyHeader();
cfg.AllowAnyMethod();
});
options.AddPolicy(name: "AnyOrigin",
cfg => {
cfg.AllowAnyOrigin();
cfg.AllowAnyHeader();
cfg.AllowAnyMethod();
});
});
Compare the default policy, which reads an allowed origin from configuration, with the named AnyOrigin policy. Both allow any header and method, but the named policy also allows any origin; choose the rule that fits the endpoint. section 3.1.1
A GET-only endpoint
Suppose the versioned /cod/test Minimal API route should accept cross-origin GET requests but not other methods. Define an AnyOrigin_GetOnly policy that allows any origin and header but only GET, then assign it to that route. Test from a browser page at another origin to check the intended request. section 3.4.1 section 3.1.1




