liveBook · Manning

EnableCors

As explained in Building Web APIs with ASP.NET Core

The EnableCors attribute is an ASP.NET Core MVC attribute that enables cross-origin resource sharing for an endpoint or controller.

`[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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Shows named-policy registration and attribute placement, while treating middleware and endpoint routing as alternative application methods.
Examples
Uses Minimal API error endpoints and a JavaScript-response endpoint annotated with `EnableCors("AnyOrigin")`.
What it assumes
Builds on `Program.cs` endpoint mappings and registered CORS policies, then shows where to place the attribute.
What you can do after
Apply it via ASP.NET Core attributes to select a registered CORS policy for a targeted endpoint.
How it connects
Connects CORS policies to Minimal APIs, controllers, endpoint routing, middleware, and credential-related security restrictions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.