What is CORS, and how do you configure it in ASP.NET Core?

Web API & REST HTTP Intermediate 1–2 Yrs2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism: by default a page can't read responses from a different origin. The server opts specific origins in by returning Access-Control-Allow-* headers. In ASP.NET Core you configure a policy with AddCors and apply it with UseCors (after UseRouting, before UseAuthorization).

CORS is a browser rule: JavaScript on one origin can't read a response from a different origin unless that server explicitly allows it with Access-Control-Allow-Origin and related headers. For anything beyond a simple GET, the browser sends a preflight OPTIONS request first and the server has to respond with the allowed origin, methods and headers. In ASP.NET Core I define a named policy in AddCors with WithOrigins listing my front-end URLs, and call UseCors between routing and authorization. Two things people get wrong: it's enforced by the browser only — Postman doesn't care — and it's not authentication, it's just about which sites can read the response.

  • Same-origin = same scheme + host + port. A React app on localhost:5173 calling an API on localhost:5001 is cross-origin.
  • For non-simple requests the browser sends a preflight OPTIONS request first; the server must answer with the allowed origin, methods and headers.
  • Policy: WithOrigins("https://app.example.com").AllowAnyHeader().AllowAnyMethod(); add .AllowCredentials() only with an explicit origin list (you can't combine it with AllowAnyOrigin).
  • CORS is enforced by the browser, not the server — tools like curl/Postman ignore it. It is not a substitute for authentication.
  • A “CORS error” in the console usually means the server didn't return the expected header (or the API itself returned a 500 on the preflight).