CORS Handling Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in C# as in every other language.
- ✓ASP.NET Core carries first-party CORS in Microsoft.AspNetCore.Cors. builder.Services.AddCors registers the service; CorsPolicyBuilder composes a policy through WithOrigins, WithMethods, WithHeaders, WithExposedHeaders, AllowCredentials and SetPreflightMaxAge(TimeSpan); app.UseCors(name) inserts the middleware, which answers the preflight itself and short-circuits the rest of the pipeline.
- ✓Placement is the reviewable detail. UseCors belongs after UseRouting and before UseAuthorization and the endpoint mapping, because a policy attached to an endpoint as metadata can only be read by a CORS middleware that runs once routing has already selected that endpoint.
- ✓The C# trap: WithOrigins matches the Origin header by ordinal string comparison, and an origin is scheme, host and port with nothing else.
- ✓Policies are built once at startup and resolved by name through ICorsPolicyProvider, so each request pays an ordinal comparison across the configured origins plus four or five writes into the response header dictionary, which stores StringValues and avoids allocating for a single value.
What CORS Handling actually is
CORS Handling in C#: what you actually reach for
C# implementation
using System;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization();
builder.Services.AddCors(options =>
{
options.AddPolicy("dashboard", policy =>
{
// Ordinal comparison against the Origin header. An origin is scheme, host and
// port: no trailing slash, no path, and the browser always sends it lowercased.
policy.WithOrigins("https://app.example.dev", "https://ops.example.dev")
.WithMethods("GET", "POST", "PATCH", "DELETE")
.WithHeaders("Content-Type", "Authorization")
.WithExposedHeaders("X-Request-Id", "X-Rate-Limit-Remaining")
.AllowCredentials() // AllowAnyOrigin here would throw
.SetPreflightMaxAge(TimeSpan.FromMinutes(10));
});
});
var app = builder.Build();
app.UseRouting();
app.UseCors("dashboard"); // after routing, before authorization: the order is the feature
app.UseAuthorization();
app.MapGet("/seats", (HttpContext ctx) =>
{
ctx.Response.Headers["X-Request-Id"] = "req-91f3";
return Results.Json(new { seats = 12 });
}).RequireCors("dashboard");
app.MapPatch("/seats", () => Results.Json(new { seats = 11 }))
.RequireCors("dashboard"); // the middleware answers this route's preflight itself
app.Run();Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for CORS Handling?
ASP.NET Core carries first-party CORS in Microsoft.AspNetCore.Cors. builder.Services.AddCors registers the service; CorsPolicyBuilder composes a policy through WithOrigins, WithMethods, WithHeaders, WithExposedHeaders, AllowCredentials and SetPreflightMaxAge(TimeSpan); app.UseCors(name) inserts the middleware, which answers the preflight itself and short-circuits the rest of the pipeline. Endpoints opt in with .RequireCors(name) or the [EnableCors] attribute, and SetIsOriginAllowed(Func<string, bool>) is the documented escape hatch for wildcard subdomains. Nothing here is a NuGet add-on: the package ships inside the shared framework.
What is the most common C# mistake when implementing CORS Handling?
WithOrigins matches the Origin header by ordinal string comparison, and an origin is scheme, host and port with nothing else. A trailing slash, the http form, a differing port or a capital letter in the host all match nothing, and browsers always emit the value lowercased. Nothing surfaces the miss. The policy runs, matches no origin, attaches no Access-Control-Allow-Origin and hands back an entirely ordinary status code, so the service looks healthy from every angle except the browser console. Its companion is calling UseCors after MapControllers, where it never executes for those endpoints.
How does CORS Handling actually perform in C#?
Policies are built once at startup and resolved by name through ICorsPolicyProvider, so each request pays an ordinal comparison across the configured origins plus four or five writes into the response header dictionary, which stores StringValues and avoids allocating for a single value. Preflights short-circuit ahead of model binding, filters and endpoint execution, so they cost a fraction of a real request. SetPreflightMaxAge is the only lever that removes work: without it the specification's default cache entry lives five seconds, and mutating calls pay two round trips. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.