skip to content

The storefront's console shows a CORS error, yet the ASP.NET Core API logged 200 and saved the subscription change — why, and how do you diagnose the policy?

level: seniorimportance: should knowfreq 38%

answer

  1. the browser blocks reading, not sending
  2. CorsMiddleware omits headers, never rejects
  3. preflight with a policy always 204
  4. Microsoft.AspNetCore.Cors at Information
  5. methods and headers checked by the browser

basics

~10 s

ASP.NET Core's CORS middleware never rejects a request: for a disallowed origin it just omits the Access-Control headers, the endpoint still runs, and the browser hides the response. Diagnose with Microsoft.AspNetCore.Cors logs at Information.

solid answer

~40 s

`CorsMiddleware` is not a gatekeeper. For a non-preflight request it registers a callback that adds headers when the response starts and then calls the endpoint; if the origin is not allowed, the callback adds nothing, so the handler runs and the write is saved while the browser withholds the response from script. For a preflight it always answers `204` once a policy is found, adding the allow headers only when the origin passes. To diagnose, raise `Microsoft.AspNetCore.Cors` to `Information` (the template sets `Microsoft.AspNetCore` to `Warning`) and look for "CORS policy execution failed" and "No CORS policy found"; compare the logged `Origin` exactly with `WithOrigins`; and check the preflight's `Access-Control-Allow-Methods`/`-Headers`, because the server echoes its lists without validating them and the browser does the final check. State-changing endpoints need authorization and CSRF defences, not CORS.

code

json · 9 lines
json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.AspNetCore.Cors": "Information"
    }
  }
}

go deeper

for a junior

Remember that a CORS error is the browser refusing to show the response; the API may well have processed the request.

for a middle

Explain the preflight 204, the OnStarting header callback, and why only the origin is checked on the server.

for a senior

Diagnose from Microsoft.AspNetCore.Cors logs and the preflight response, and make sure writes are protected by authorization and antiforgery rather than CORS.

for a principal

Set the expectation across teams that CORS is a browser read contract, and decide where origin checks are logged for observability without treating them as security.

## What the middleware actually does `CorsMiddleware` only decides **which headers to add**. It never sends `403` and never stops a request on its own. The code path for a request that carries an `Origin` header: 1. Resolve a policy (endpoint metadata, then the middleware's policy, then the default policy). 2. Call `ICorsService.EvaluatePolicy`, which checks **only the origin** against the policy and fills a `CorsResult`. 3. **Preflight** (`OPTIONS` + `Access-Control-Request-Method`): apply the result and end with **`204 No Content`**. If the origin failed, the `204` simply carries no CORS headers, and the browser cancels the real request. 4. **Any other request**: register an `OnStarting` callback that applies the result, then **call the next middleware**. The endpoint runs. If the origin failed, the callback writes nothing. So the browser's error and the server's `200` are both true: the server did the work, and the browser refused to give the response to the storefront's script. ## Why a write can land without a preflight A browser sends some cross-origin requests without asking first: a `POST` whose `Content-Type` is `application/x-www-form-urlencoded`, `multipart/form-data` or `text/plain`, with only safelisted headers. Such a request reaches the endpoint directly. Either way, the browser checks the actual response's CORS headers only after the handler has executed. ## The diagnosis, step by step 1. **Make the CORS logs visible.** The template's `appsettings.json` sets `"Microsoft.AspNetCore": "Warning"`, which hides the CORS messages; they are logged at **Information** under `Microsoft.AspNetCore.Cors.Infrastructure.*`. Add `"Microsoft.AspNetCore.Cors": "Information"`. 2. **Read the messages.** | Log message | Meaning | |---|---| | CORS policy execution successful. | the origin matched; headers were or will be written | | CORS policy execution failed. / Request origin X does not have permission to access the resource. | origin not in the policy | | No CORS policy found for the specified request. | no policy resolved: a misspelt name, or `UseCors()` with no default policy | | Failed to apply CORS Response headers. | the `OnStarting` callback threw (Warning) | 3. **Compare origins character by character**: scheme, host, port, a trailing slash in `WithOrigins`, `www.` versus bare host. 4. **Check the preflight response in the browser's network panel.** ASP.NET Core does **not** compare the requested method or headers with the policy; it writes the policy's lists (or echoes them under `AllowAnyMethod`/`AllowAnyHeader`) and lets the browser decide. A policy without `WithHeaders("Content-Type")` therefore logs "successful" while the browser rejects a JSON `POST`. 5. **Check redirects.** A preflight that `UseHttpsRedirection` answers with a redirect fails in the browser; call the API over `https` directly. ## A worked trace Take the storefront's "change roast" button, which sends `PUT /api/subscriptions/42` as JSON from `https://shop-staging.coffee.example` while the policy lists only production: 1. The browser sends a preflight. `CorsMiddleware` finds the policy, the origin fails, and it answers `204 No Content` without headers. The browser never sends the `PUT`. 2. A teammate "fixes" the client by switching to a body-less `POST /api/subscriptions/42/pause` with no custom headers. That request needs no preflight, so it goes straight out. 3. `CorsMiddleware` registers its header callback and calls the endpoint. The handler updates the row and returns `200`. 4. The callback finds the origin was not allowed and writes no `Access-Control-Allow-Origin`. The browser blocks the script from reading the `200`, and the console shows a CORS error. The change was saved by step 3. The correct fix is to add the staging origin to the staging policy, not to change the request shape until the preflight disappears. ## The design lesson - CORS controls **who may read**, not **who may write**. An endpoint that changes data must enforce **authorization**, and with cookie authentication also **antiforgery** or another CSRF defence. - Do not try to make `CorsMiddleware` return `403` for unknown origins as a security measure: non-browser clients send no `Origin` or any `Origin` they like. - If you want rejection for observability, log it; keep the policy itself as the browser contract.

  • The ASP.NET Core log says 'CORS policy execution successful', but the browser still rejects the preflight. What do you check?
    That message only means the origin matched. ASP.NET Core does not validate the requested method or headers; it writes the policy's `Access-Control-Allow-Methods` and `-Headers` and the browser compares them. Look at the preflight response: a JSON `POST` needs `content-type` in the allowed headers (`WithHeaders("Content-Type")` or `AllowAnyHeader()`), and a `PUT` needs `WithMethods("PUT")` or `AllowAnyMethod()`.
  • Should you make the ASP.NET Core API return 403 for unknown origins to stop unwanted writes?
    It would not stop them. Server-to-server callers and scripts set any `Origin` they like or none at all, so an `Origin` check is not access control. Protect the write with `[Authorize]` or `RequireAuthorization`, and with antiforgery when the API trusts cookies; keep CORS as the contract that tells browsers who may read responses.

A kitchen that cooks every order phoned in, while the delivery driver refuses to hand it over at a door that is not on the approved list: the meal was still made and the ingredients used up.

  • A CORS error means the ASP.NET Core endpoint never ran.
  • CorsMiddleware rejects disallowed origins with 403 before the handler runs.
  • 'CORS policy execution successful' proves the preflight's methods and headers were accepted.
  • Adding a strict CORS policy protects a cookie-authenticated POST endpoint from CSRF.
  • The template's logging already shows CORS decisions by default.