skip to content

In ASP.NET Core 10, when UseCors, RequireCors and [EnableCors] or [DisableCors] all apply to one endpoint, which decides its CORS behaviour?

level: middleimportance: should knowfreq 42%

answer

  1. endpoint metadata beats middleware
  2. most specific ICorsMetadata wins
  3. [DisableCors]: preflight 204, no headers
  4. unnamed [EnableCors] uses the default policy
  5. metadata without UseCors throws

basics

~20 s

Endpoint metadata wins: [DisableCors] switches CORS off, RequireCors or [EnableCors("name")] picks that policy, and only otherwise does the policy given to UseCors (or the default policy) apply. An unknown policy name just yields no CORS headers.

solid answer

~40 s

`CorsMiddleware` reads the endpoint's most specific `ICorsMetadata`. `[DisableCors]` turns CORS off: a preflight gets `204` with no CORS headers and other requests pass through untouched. An inline policy from `RequireCors(p => ...)` is used as is. A name from `RequireCors("Partners")` or `[EnableCors("Partners")]` overrides whatever was passed to `UseCors`. If the endpoint has no metadata, or an unnamed `[EnableCors]`/`RequireCors()`, the middleware's own policy applies: the inline one from `UseCors(p => ...)`, the name from `UseCors("Storefront")`, or for `UseCors()` the policy from `AddDefaultPolicy`. A name that matches no policy logs "No CORS policy found" and sends no headers. And an endpoint carrying CORS metadata in an app that never called `UseCors` throws `InvalidOperationException`.

code

csharp · 15 lines
csharp
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(p => p.WithOrigins("https://shop.coffee.example"));
    options.AddPolicy("Partners", p => p.WithOrigins("https://partner.example.org").WithMethods("GET"));
});

var app = builder.Build();
app.UseCors(); // no name: falls back to the default policy

app.MapGet("/api/plans", () => "plans");                              // default policy
app.MapGet("/api/catalog", () => "catalog").RequireCors("Partners");  // named policy wins
app.MapPost("/api/webhooks/roaster", () => Results.Ok())
   .WithMetadata(new DisableCorsAttribute());                         // never CORS-enabled

app.Run();

go deeper

for a junior

Know that RequireCors and [EnableCors] pick a policy per endpoint, and [DisableCors] switches CORS off for one endpoint.

for a middle

Walk through the order: endpoint metadata first, then the UseCors policy, then the default policy, and what a missing name or missing UseCors does.

for a senior

Design route groups so each caller's policy is attached once, and catch silent misses from misspelt names by raising the Microsoft.AspNetCore.Cors log level when diagnosing.

for a principal

Decide whether CORS policy belongs in code per endpoint or centrally per gateway, and how teams keep many services' origin lists consistent.

## Three places a policy can come from ASP.NET Core lets you choose a CORS policy at two levels: - **The middleware level**: `app.UseCors()`, `app.UseCors("Storefront")` or `app.UseCors(p => ...)`. This is the fallback for every request that reaches the middleware. - **The endpoint level**: metadata attached to a route. For Minimal APIs and route groups that is `RequireCors()`, `RequireCors("name")` or `RequireCors(p => ...)`; for controllers, Razor Pages and Minimal API lambdas it is the `[EnableCors]`, `[EnableCors("name")]` and `[DisableCors]` attributes from `Microsoft.AspNetCore.Cors`. - **The policy store**: `CorsOptions`, filled by `AddPolicy` and `AddDefaultPolicy`, and read through `ICorsPolicyProvider`. All three endpoint forms implement `ICorsMetadata`, and the middleware asks the endpoint for the **most significant** one, which is the last added. An attribute on an action therefore beats one on its controller, and metadata on an endpoint beats metadata on its `MapGroup`. ## The resolution order in `CorsMiddleware` 1. **No `Origin` header**: the request is not cross-origin; the middleware calls the next component and does nothing else. 2. **`[DisableCors]`**: if the request is a preflight (`OPTIONS` with `Access-Control-Request-Method`), the middleware answers **`204 No Content` with no CORS headers**; any other request passes through with no headers. 3. **Inline endpoint policy** from `RequireCors(p => ...)`: used directly. 4. **Named endpoint policy** from `RequireCors("name")` or `[EnableCors("name")]`: overrides the middleware's policy. 5. **Otherwise** (no metadata, or an unnamed `[EnableCors]`/`RequireCors()`): the middleware's inline policy, else its policy name, else `CorsOptions.DefaultPolicyName`, which is where `AddDefaultPolicy` stored its policy. 6. **No policy found**: the default `ICorsPolicyProvider` returns `null`, the middleware logs "No CORS policy found for the specified request." at Information level and continues without headers. | Endpoint carries | Policy used | |---|---| | nothing | the policy given to `UseCors`, or the default policy for `UseCors()` | | `[EnableCors]` / `RequireCors()` | same as above | | `[EnableCors("Partners")]` / `RequireCors("Partners")` | `Partners`, regardless of `UseCors("Storefront")` | | `RequireCors(p => p.WithOrigins(...))` | that inline policy | | `[DisableCors]` | none; preflight answered `204` with no headers | ## Two failure modes to recognise - **A misspelt name fails quietly.** `RequireCors("Partner")` when the policy is `Partners` does not throw: the provider finds nothing and no `Access-Control-*` headers are written. With the template's `"Microsoft.AspNetCore": "Warning"` log level the Information message is hidden too. - **Metadata without middleware fails loudly.** If an endpoint carries any `ICorsMetadata` and `CorsMiddleware` never ran, `EndpointMiddleware` throws `InvalidOperationException`: "Endpoint ... contains CORS metadata, but a middleware was not found that supports CORS." The fix is to add `app.UseCors()`. ## Preflight routing comes for free A Minimal API endpoint such as `app.MapPost("/api/subscriptions", ...)` only matches `POST`. When the endpoint has CORS metadata, routing marks its HTTP-method metadata with `AcceptCorsPreflight = true`, so the browser's `OPTIONS` preflight is matched to it and the middleware can answer. You do not need a separate `MapMethods(..., ["OPTIONS"], ...)` or an `[HttpOptions]` action for it. ## Choosing a style - **One policy for the whole API**: `AddDefaultPolicy` plus `UseCors()`, and `[DisableCors]` on the few endpoints that must never be read cross-origin, such as a webhook receiver. - **Different callers on different routes**: `UseCors()` with no default policy, and `RequireCors("Storefront")` on a `MapGroup("/api/shop")`, `RequireCors("Partners")` on `/api/catalog`. - **Controllers**: `[EnableCors("Storefront")]` on the controller and `[DisableCors]` on the one action that must opt out. `[DisableCors]` is not inherited by derived classes (`Inherited = false`), while `[EnableCors]` is. - There is no `DisableCors()` extension method; for a Minimal API endpoint put `[DisableCors]` on the lambda or call `WithMetadata(new DisableCorsAttribute())`. ## Seeing which policy ran When a policy seems to be ignored, check the decision rather than guessing: 1. Raise `Microsoft.AspNetCore.Cors` to `Information` and look for "No CORS policy found for the specified request." versus "CORS policy execution successful.". 2. Inspect the endpoint's metadata in a test or at startup: `EndpointDataSource` lists each endpoint, and `endpoint.Metadata.GetMetadata<ICorsMetadata>()` returns the entry the middleware will use. 3. Remember precedence when a route group and an endpoint both carry metadata: group conventions are applied first, so the endpoint's own `RequireCors` or `[DisableCors]` is the more specific one. Most "the policy is ignored" reports end at step 1: a name typed differently in `AddPolicy` and `RequireCors`, or `UseCors()` called with no default policy registered.

  • What does ASP.NET Core do when RequireCors names a policy that was never registered?
    Nothing visible. `DefaultCorsPolicyProvider` returns `null` for an unknown name, so `CorsMiddleware` logs "No CORS policy found for the specified request." at Information level and passes the request on without any `Access-Control-*` headers. The browser then reports a CORS failure while the server shows no error.
  • Why does a cross-origin preflight reach a MapPost endpoint that has RequireCors, when that endpoint only accepts POST?
    When an endpoint carries CORS metadata, `RouteEndpointBuilder` sets `AcceptCorsPreflight = true` on its HTTP-method metadata. Routing then matches an `OPTIONS` request carrying `Access-Control-Request-Method` to the endpoint, and `CorsMiddleware` answers it with `204` before the handler would run.

  • UseCors("Storefront") always wins over a policy named on the endpoint.
  • A misspelt policy name in RequireCors throws at startup.
  • [DisableCors] makes the CORS middleware reject the request with 403.
  • A POST-only endpoint needs an extra OPTIONS route for preflights to work.
  • Call DisableAntiforgery() on the endpoint to switch CORS off.