`[EnableCors]` applies a CORS policy to an ASP.NET Core endpoint or controller. CORS controls which browser-based clients from other origins may access an API. Use the attribute when a particular endpoint needs a policy, rather than applying that policy to every endpoint. section 3.1.1
To use a named policy:
- Register the policy with `builder.Services.AddCors(...)`. A policy can specify allowed origins, headers, and methods. section 3.1.1
- Place `[EnableCors("AnyOrigin")]` on the endpoint that should use the named policy. Minimal API endpoints can put the attribute before their handler. section 3.1.1
- Choose the policy deliberately: `AnyOrigin` permits requests from any origin, so it is not a good blanket choice for the board-game controller when access should be restricted. section 3.1.1
A targeted endpoint
The `/cod/test` Minimal API endpoint uses `[EnableCors("AnyOrigin")]` alongside `[ResponseCache(NoStore = true)]`. The first attribute selects its CORS policy; the second prevents clients and proxies from caching its HTML response. Opening the URL checks the JavaScript demonstration, but that direct visit alone does not establish whether a cross-origin request is permitted. section 3.1.5 section 3.1.1
For application-wide behavior, CORS middleware can apply a policy to all endpoints instead. Endpoint routing offers another way to attach a policy. Credentials require extra care: a wildcard origin cannot be used with requests that include cookies, authorization headers, or TLS client certificates. section 3.1.1
// ...
// Minimal API
app.MapGet("/error", [EnableCors("AnyOrigin")] () =>
Results.Problem());
app.MapGet("/error/test", [EnableCors("AnyOrigin")] () =>
{ throw new Exception("test"); });
// ...
The listing shows `[EnableCors("AnyOrigin")]` attached directly to two Minimal API handlers. section 3.1.1
