Typical Browser Console Error (React Frontend → ASP.NET Core Web API)
When cross-origin headers are missing, mismatched, or blocked during preflight between React Frontend and ASP.NET Core Web API, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'https://localhost:7001/api/invoices' from origin 'http://localhost:5173' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:5173/' that is not equal to the supplied origin.
Why CORS Blocks Requests Between React Frontend and ASP.NET Core Web API
Running an ASP.NET Core 8 or 9 Minimal API or Controller-based Web API alongside a React frontend (served via Vite on port 5173 or Create React App on port 3000) is a proven architecture for modern SaaS dashboards and enterprise portals. Because React runs on its own Node.js development server while .NET runs on Kestrel, browsers classify every fetch() or Axios request as cross-origin and strictly verify scheme, hostname, and port equality before permitting JavaScript to inspect any response.
In ASP.NET Core Minimal APIs, CORS can be enabled globally via app.UseCors(policyName) or scoped per endpoint with .RequireCors(policyName). A frequent mistake engineers make when configuring WithOrigins("http://localhost:5173/") is assuming .NET automatically normalizes trailing slashes. In reality, ASP.NET Core performs an exact string comparison against Chrome's Origin: http://localhost:5173 header, so a single stray trailing slash breaks every preflight and actual request silently.
React developers integrating with ASP.NET Core also routinely run into two non-obvious traps: untrusted local .NET HTTPS development certificates (which abort the TLS handshake with ERR_CERT_AUTHORITY_INVALID before CORS even executes) and missing Access-Control-Expose-Headers when React attempts to read X-Pagination totals or Content-Disposition filenames returned by .NET FileResult endpoints.
Whether you ship ASP.NET Core 8 and 9 Minimal APIs or traditional MVC controllers behind a React SPA, validating origin formatting, TLS certificates, and exposed headers early prevents the most time-consuming cross-origin bugs in .NET web stacks. Verify that every entry in WithOrigins() omits trailing slashes and paths, that app.UseCors() executes between app.UseRouting() and app.UseAuthentication(), and that custom response headers like X-Pagination or Content-Disposition are listed in WithExposedHeaders() before React attempts to read them. Running a quick OPTIONS preflight check via curl or the simulator above confirms your Kestrel headers match Fetch Standard requirements before deploying to production.
Step-by-Step ASP.NET Core Web API + React Frontend CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for ASP.NET Core Web API.
1Define a Strict ASP.NET Core CORS Policy Without Trailing Slashes
Program.csConfigure AddCors() with exact React origins (verified with zero trailing slashes), explicit HTTP methods, explicit request headers, and WithExposedHeaders() so React can read custom headers such as X-Pagination or Content-Disposition for invoice PDF downloads.
Program.cscsharpconst string ReactPolicy = "ReactSpaCors"; var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(options => { options.AddPolicy(ReactPolicy, policy => { policy.WithOrigins("http://localhost:5173") .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") .WithHeaders("Content-Type", "Authorization") .WithExposedHeaders("Content-Disposition", "X-Pagination") .SetPreflightMaxAge(TimeSpan.FromSeconds(86400)); }); }); var app = builder.Build(); app.UseRouting(); app.UseCors(ReactPolicy); app.UseAuthentication(); app.UseAuthorization(); app.MapPost("/api/invoices", (object invoice) => Results.Created("/api/invoices/1", invoice)) .RequireCors(ReactPolicy); app.Run();2Trust the .NET Local HTTPS Development Certificate
terminalWhen React runs on http://localhost:5173 and calls Kestrel on https://localhost:7001, an untrusted self-signed cert aborts the TLS handshake before HTTP headers are exchanged; causing fetch() to reject with TypeError: Failed to fetch. Trust the ASP.NET Core development certificate once per workstation.
terminalbashdotnet dev-certs https --trust3Support Dynamic Staging Subdomains Safely Using SetIsOriginAllowed
Program.csIf your React frontend deploys preview branches on subdomains, never fall back to AllowAnyOrigin() in production. Instead, parse the incoming URI inside SetIsOriginAllowed and verify both the HTTPS scheme and your exact root domain suffix so untrusted lookalike domains are rejected.
Program.cscsharppolicy.SetIsOriginAllowed(origin => { if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri)) return false; return uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || (uri.Scheme == Uri.UriSchemeHttps && uri.Host.EndsWith(".myapp.com", StringComparison.OrdinalIgnoreCase)); });4Call the .NET Minimal API Cleanly From React With Environment Config
src/api/invoices.tsBind your API base URL through VITE_DOTNET_API_URL so staging and production builds automatically target your deployed Kestrel/container origin without hardcoding localhost ports inside React components.
src/api/invoices.tstypescriptconst API_BASE = import.meta.env.VITE_DOTNET_API_URL ?? 'https://localhost:7001'; export async function createInvoice(token: string, amountCents: number) { const response = await fetch(`${API_BASE}/api/invoices`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify({ amountCents }), }); if (!response.ok) { throw new Error(`ASP.NET Core returned HTTP ${response.status}`); } return response.json(); }
Common ASP.NET Core Web API + React Frontend CORS Pitfalls
Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.
Trailing Slash in WithOrigins("http://localhost:5173/")
ASP.NET Core performs an exact case-insensitive string match on origins. Leaving a trailing slash prevents the policy from matching Chrome's Origin: http://localhost:5173 header, omitting Access-Control-Allow-Origin and blocking every browser call.
Forgetting app.UseCors() When Using [EnableCors] or .RequireCors()
Decorating an API controller with [EnableCors("ReactSpaCors")] or a Minimal API endpoint with .RequireCors("ReactSpaCors") has zero effect unless app.UseCors() is actually registered in the middleware pipeline inside Program.cs.
Broken Preflight Responses Caused by Custom Authorization Filters or Minimal API Endpoint Filters
Global MVC filters or custom API-key middleware that inspect Authorization headers before app.UseCors() executes will reject anonymous OPTIONS preflights with HTTP 401 or 403. Keep UseCors() ahead of authentication and custom request guards.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your Proxy
Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Reverse Proxy Config for ASP.NET Core Kestrel (Forwarded Headers & SignalR).
Frequently Asked Questions
- What is the difference between app.UseCors("Policy") and .RequireCors("Policy") in .NET 8/9?
- Passing a policy name directly to app.UseCors("Policy") applies that policy globally to every endpoint in the application. Calling app.UseCors() without arguments enables endpoint-level CORS so only endpoints annotated with [EnableCors("Policy")] or .RequireCors("Policy") emit CORS headers.
- Why does React throw TypeError: Failed to fetch with zero response status when calling https://localhost:7001?
- First confirm the .NET HTTPS dev certificate is trusted by running dotnet dev-certs https --trust or opening https://localhost:7001/swagger directly in your browser. Untrusted TLS certificates terminate the connection before HTTP or CORS headers are ever exchanged.
- How do I let React read Content-Disposition for PDF downloads from ASP.NET Core?
- Chain .WithExposedHeaders("Content-Disposition") onto your ASP.NET Core CORS policy inside AddCors(). Otherwise, browsers hide Content-Disposition from response.headers.get() in cross-origin fetch calls even when visible in DevTools.
- Does ASP.NET Core automatically add Vary: Origin?
- Yes. Whenever your policy specifies explicit origins via WithOrigins() or SetIsOriginAllowed(), ASP.NET Core's CorsService automatically attaches Vary: Origin to responses so CDNs and browser caches stay origin-safe.
Related CORS Stack Simulators
Browse all 12 stacks →ASP.NET Core 8/9 + Angular CORS Config Simulator & Fix Guide
Fix CORS errors between ASP.NET Core 8/9 Web API and Angular CLI on port 4200. Verify UseCors middleware ordering, AllowCredentials, and HTTPS redirects.
Laravel + React (Vite) CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between Laravel 11/12 APIs and React Vite on port 5173. Generate config/cors.php with credentials and header rules.
FastAPI + React (Vite) CORS Config Simulator & Fix Guide
Simulate and resolve CORS errors between Python FastAPI and React Vite on port 5173. Fix preflight OPTIONS failures, Pydantic 422 responses, and upload headers.
Node.js Express + React (Vite) CORS Config Simulator & Fix Guide
Resolve CORS preflight errors between Node.js Express APIs and React Vite on port 5173. Generate cors() configs, fix PATCH/DELETE methods, and debug headers.