CORS
Browsers enforce the same-origin policy: JavaScript loaded from https://app.example.com may not read responses from https://api.example.com, because the two have different origins (scheme + host + port). CORS — Cross-Origin Resource Sharing — is how a server tells the browser "this other origin is allowed to read my responses".
Note: CORS is enforced by browsers only.
curl, Postman, mobile apps and other servers ignore it completely. It is not a security feature for your API — it relaxes a browser restriction. Protect your data with authentication and authorization.
Same origin or not?
using System;
(string Scheme, string Host, int Port) Origin(string url)
{
var u = new Uri(url);
return (u.Scheme, u.Host, u.Port);
}
var page = "https://app.example.com/index.html";
string[] targets =
{
"https://app.example.com/api/notes",
"http://app.example.com/api/notes",
"https://api.example.com/notes",
"https://app.example.com:8443/notes",
};
foreach (var t in targets)
{
bool same = Origin(page) == Origin(t);
Console.WriteLine(quot;{t,-38} {(same ? "same origin" : "cross-origin -> needs CORS")}");
}https://app.example.com/api/notes same origin
http://app.example.com/api/notes cross-origin -> needs CORS
https://api.example.com/notes cross-origin -> needs CORS
https://app.example.com:8443/notes cross-origin -> needs CORS
Enabling CORS in ASP.NET Core
Register named policies with AddCors, then add the middleware with UseCors. It must run after UseRouting (if you call it) and before authentication/authorization, so that preflight requests are answered even for protected endpoints.
var builder = WebApplication.CreateBuilder(args);
const string Frontend = "Frontend";
builder.Services.AddCors(options =>
{
options.AddPolicy(Frontend, policy => policy
.WithOrigins("http://localhost:5173", "https://app.example.com")
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Content-Type", "Authorization")
.WithExposedHeaders("X-Total-Count")
.SetPreflightMaxAge(TimeSpan.FromMinutes(10)));
options.AddPolicy("PublicRead", policy => policy
.AllowAnyOrigin()
.WithMethods("GET"));
});
var app = builder.Build();
app.UseCors(); // no default policy: endpoints opt in below
app.MapGet("/notes", () => new[] { new { id = 1, text = "Hi" } })
.RequireCors(Frontend);
app.MapGet("/status", () => "ok")
.RequireCors("PublicRead");
app.Run();Alternatively call app.UseCors(Frontend) to apply one policy to every endpoint, or use [EnableCors("Frontend")] / [DisableCors] on controllers.
| Builder method | Response header it controls |
|---|---|
WithOrigins(...) / AllowAnyOrigin() |
Access-Control-Allow-Origin |
WithMethods(...) / AllowAnyMethod() |
Access-Control-Allow-Methods (preflight) |
WithHeaders(...) / AllowAnyHeader() |
Access-Control-Allow-Headers (preflight) |
WithExposedHeaders(...) |
Access-Control-Expose-Headers |
AllowCredentials() |
Access-Control-Allow-Credentials: true |
SetPreflightMaxAge(...) |
Access-Control-Max-Age |
Note: Origins must match exactly —
https://app.example.com/with a trailing slash never matches, because browsers send the origin without one.
Simple requests and preflights
For "simple" requests (a GET, or a POST with a form content type), the browser sends the request with an Origin header and checks the response's Access-Control-Allow-Origin. For anything else — PUT/DELETE, a JSON body, an Authorization header — it first sends an OPTIONS preflight asking for permission.
You can imitate both with curl:
$ curl -si localhost:5000/notes -H "Origin: http://localhost:5173"
$ curl -si -X OPTIONS localhost:5000/notes -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: PUT" -H "Access-Control-Request-Headers: content-type"
$ curl -si -X OPTIONS localhost:5000/notes -H "Origin: https://evil.example" -H "Access-Control-Request-Method: DELETE"HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Expose-Headers: X-Total-Count
Vary: Origin
Transfer-Encoding: chunked
[{"id":1,"text":"Hi"}]
HTTP/1.1 204 No Content
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET,POST,PUT,DELETE
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Max-Age: 600
Vary: Origin
HTTP/1.1 204 No Content
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
The rejected preflight still gets a 204, but without any Access-Control-Allow-* headers — so the browser refuses to send the real DELETE, and the page's fetch fails with a CORS error in the console.
What the middleware decides
Here is the core of the decision as plain C#: compare the request's Origin, method and headers against the policy and build the response headers.
using System;
using System.Collections.Generic;
using System.Linq;
var policy = new CorsPolicy(
Origins: new[] { "http://localhost:5173", "https://app.example.com" },
Methods: new[] { "GET", "POST", "PUT", "DELETE" },
Headers: new[] { "content-type", "authorization" });
void Preflight(string origin, string method, params string[] headers)
{
var response = new List<string>();
bool ok = policy.Origins.Contains(origin)
&& policy.Methods.Contains(method)
&& headers.All(h => policy.Headers.Contains(h.ToLowerInvariant()));
if (ok)
{
response.Add(quot;Access-Control-Allow-Origin: {origin}");
response.Add(quot;Access-Control-Allow-Methods: {string.Join(",", policy.Methods)}");
}
Console.WriteLine(quot;{origin} {method} -> {(ok ? "allowed" : "blocked")}");
foreach (var line in response) Console.WriteLine(" " + line);
}
Preflight("http://localhost:5173", "PUT", "Content-Type");
Preflight("https://evil.example", "DELETE");
Preflight("https://app.example.com", "PATCH");
record CorsPolicy(string[] Origins, string[] Methods, string[] Headers);http://localhost:5173 PUT -> allowed
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET,POST,PUT,DELETE
https://evil.example DELETE -> blocked
https://app.example.com PATCH -> blocked
Credentials
If the browser must send cookies (fetch(url, { credentials: "include" })), the policy needs AllowCredentials() and explicit origins. ASP.NET Core throws at startup if you combine AllowAnyOrigin() with AllowCredentials(), because the CORS spec forbids * with credentials.
Tip: In development, a Vite or Angular dev-server proxy often avoids CORS entirely: the page and the API appear under the same origin.
Test yourself
Who enforces CORS?
- Kestrel
- The browser
- The operating system firewall
- curl
Which request triggers a preflight OPTIONS call?
- A plain
GETwith no custom headers - Loading an
<img>from another site - A
PUTwith a JSON body - Following a link
Why does AllowAnyOrigin().AllowCredentials() fail?
- The spec forbids the
*origin together with credentials - Credentials need HTTP/3
- AllowAnyOrigin only works in Development
- It doesn't fail; it is the recommended setup