In ASP.NET Core 10, how do you let a React storefront served from another origin call your API, and what does each CORS call do?
answer
- services first, middleware second
- AddCors registers CorsOptions policies
- AddPolicy(name) vs AddDefaultPolicy
- UseCors("name") applies it per request
- WithOrigins: exact origin, no trailing slash
basics
~10 sRegister a policy with builder.Services.AddCors(o => o.AddPolicy("Storefront", p => p.WithOrigins("https://shop.coffee.example"))) and apply it with app.UseCors("Storefront"). The policy tells browsers which origins may read responses; it blocks no other client.
solid answer
~30 sTwo pieces are needed. `builder.Services.AddCors(...)` registers the CORS services and stores policies in `CorsOptions`: `AddPolicy("Storefront", ...)` creates a named policy, `AddDefaultPolicy(...)` the one used when no name is given. Inside the builder you list what the storefront needs: `WithOrigins("https://shop.coffee.example")`, `WithMethods`/`AllowAnyMethod`, `WithHeaders`/`AllowAnyHeader`, and optionally `WithExposedHeaders` and `SetPreflightMaxAge`. Then `app.UseCors("Storefront")` runs the middleware that writes the `Access-Control-*` headers and answers preflight `OPTIONS` requests with `204`. Origins are compared as exact scheme, host and port, so `https://shop.coffee.example/` with a trailing slash never matches. CORS loosens the browser's same-origin rule; it does not stop curl or another server from calling the API.
code
csharp · 20 linesvar builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("Storefront", policy => policy
.WithOrigins("https://shop.coffee.example")
.WithMethods("GET", "POST", "PUT")
.WithHeaders("Content-Type")
.WithExposedHeaders("X-Total-Count")
.SetPreflightMaxAge(TimeSpan.FromMinutes(10)));
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseCors("Storefront");
app.MapGet("/api/plans", () => TypedResults.Ok(new[] { "Weekly", "Monthly" }));
app.Run();go deeper
Recall the pair: AddCors with AddPolicy on the services, UseCors on the pipeline. Know that origins must match exactly and that CORS only governs browsers.
Explain named versus default policies, which builder calls emit which Access-Control headers, and why a preflight gets 204 with or without the allow headers.
Show you keep origin lists in configuration per environment, scope policies per caller, and never treat CORS as authorisation for a cookie-authenticated API.
Discuss whether browser callers should share one origin through a reverse proxy instead, removing CORS entirely, and what that costs in deployment coupling.
## What problem CORS solves in an ASP.NET Core app A React storefront served from `https://shop.coffee.example` and an API served from `https://api.coffee.example` are **different origins** (an origin is scheme + host + port). By default a browser lets script on the storefront *send* a request to the API but refuses to hand the response back to the script. **Cross-Origin Resource Sharing (CORS)** is the opt-in: the API adds `Access-Control-Allow-*` response headers that tell the browser which origins may read what. In ASP.NET Core the opt-in is two calls: one on the service collection and one on the pipeline. ## Step 1: register services and policies with `AddCors` `builder.Services.AddCors(options => ...)` registers `ICorsService` and `ICorsPolicyProvider` (both transient) and configures `CorsOptions`, the bag that holds your policies: - **`AddPolicy(name, configure)`** adds a **named policy**; endpoints or the middleware refer to it by that string. - **`AddDefaultPolicy(configure)`** adds the policy used when nothing names one. Internally it is stored under `CorsOptions.DefaultPolicyName`, which is `"__DefaultCorsPolicy"`. - Each policy is built with a **`CorsPolicyBuilder`**; the builder runs `Build()` as soon as the configure delegate finishes. The builder methods a storefront usually needs: | Builder call | What it adds to responses | |---|---| | `WithOrigins("https://shop.coffee.example")` | the origins whose requests get an `Access-Control-Allow-Origin` echo | | `WithMethods("GET", "POST", "PUT")` / `AllowAnyMethod()` | `Access-Control-Allow-Methods` on preflight responses | | `WithHeaders("Content-Type")` / `AllowAnyHeader()` | `Access-Control-Allow-Headers` on preflight responses | | `WithExposedHeaders("X-Total-Count")` | `Access-Control-Expose-Headers` on the actual response | | `SetPreflightMaxAge(TimeSpan.FromMinutes(10))` | `Access-Control-Max-Age` on preflight responses (none is sent unless you call it) | | `AllowCredentials()` | `Access-Control-Allow-Credentials: true`, needed when the storefront sends cookies | ## Step 2: run the middleware with `UseCors` `app.UseCors("Storefront")` adds `CorsMiddleware` with that policy as its fallback. For every request that carries an `Origin` header the middleware: 1. resolves the policy (endpoint metadata first, then the middleware's own policy); 2. for a **preflight** (`OPTIONS` plus `Access-Control-Request-Method`), writes the allowed headers when the origin is allowed and ends the request with **`204 No Content`**; 3. for any other request, registers a callback that adds the headers when the response starts, then calls the next middleware. Other overloads: `app.UseCors()` uses the default policy, and `app.UseCors(p => ...)` builds an inline policy. Per-endpoint choices (`RequireCors`, `[EnableCors]`, `[DisableCors]`) layer on top; the template does not call `UseCors` for you, and where it sits relative to authentication and caching is a middleware-order question. ## Origin matching is exact `WithOrigins` normalises each value mainly by lower-casing it (internationalised host names are also punycoded), then the default check is an **ordinal `Contains`** against the browser's `Origin` header. Consequences: - `https://shop.coffee.example/` with a **trailing slash** never matches, because browsers send the origin without one. - `http://` and `https://` are different origins, as are `:3000` and `:443`; a React dev server on `http://localhost:5173` needs its own entry, typically in a Development-only policy. - `WithOrigins("*")` is the same as `AllowAnyOrigin()`: the policy's origin list becomes the single `*` entry. ## What CORS does not do - It is **not authentication or authorisation**: a non-browser client ignores the headers entirely, so the API still needs `[Authorize]` or `RequireAuthorization` where data is private. - A disallowed origin does not get a `403`; the middleware simply omits the headers and the browser withholds the response. - It does not replace CSRF protection for cookie-authenticated, state-changing endpoints. ## A reasonable default for a SPA front end - Keep **one named policy per kind of caller** (the storefront, a partner widget) rather than one permissive default. - List origins from configuration so staging and production differ without code changes. - Prefer `WithMethods` and `WithHeaders` with the exact lists the storefront uses when the API is sensitive; `AllowAnyMethod`/`AllowAnyHeader` are acceptable for a public read API. ## Keeping environments apart The storefront usually exists in several places at once: a Vite or Next.js dev server on `localhost`, a staging site and production. A clean way to keep them apart: 1. Put the origin list in configuration, for example a `Cors:StorefrontOrigins` array in `appsettings.json` and a different one in `appsettings.Development.json`. 2. Read it once in `Program.cs` with `builder.Configuration.GetSection("Cors:StorefrontOrigins").Get<string[]>()` and pass the array to `WithOrigins`. 3. Never fall back to `AllowAnyOrigin()` "just for dev": the same code path ships to production, and the moment someone adds `AllowCredentials()` the builder throws anyway. This keeps the policy name stable (`"Storefront"`) while the list behind it changes per environment, so endpoints and attributes never need to know which environment they run in.
- What is the difference between AddPolicy and AddDefaultPolicy in ASP.NET Core's CorsOptions?`AddPolicy(name, ...)` stores a policy under the name you choose; something must refer to that name, such as `UseCors("Storefront")`, `RequireCors("Storefront")` or `[EnableCors("Storefront")]`. `AddDefaultPolicy(...)` stores it under `CorsOptions.DefaultPolicyName` (`"__DefaultCorsPolicy"`), which is what `UseCors()`, `RequireCors()` and an unnamed `[EnableCors]` resolve when no name is given.
- Why does a React dev server on http://localhost:5173 fail against a policy that lists only the production storefront?The default origin check is an exact, ordinal match on scheme, host and port, so `http://localhost:5173` is a different origin from `https://shop.coffee.example`. Add it to a policy used only in Development, for example by reading the origin list from `appsettings.Development.json`, rather than widening production with `AllowAnyOrigin()`.
- Calling AddCors alone enables CORS for every endpoint without UseCors or endpoint metadata.
- A disallowed origin gets a 403 Forbidden from the CORS middleware.
- WithOrigins("https://shop.coffee.example/") with a trailing slash is fine.
- Enabling CORS stops curl and other servers from calling the API.
- WithExposedHeaders controls which request headers the browser may send.