CORS & Preflight Simulator · ASP.NET Core Web API + React Frontend

ASP.NET Core Web API + React CORS Config Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between React Frontend and ASP.NET Core Web API. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (React Frontend)

2. Server Response Policy (ASP.NET Core Web API)

Access-Control-Allow-Methods
// Program.cs — ASP.NET Core 8/9 Web API CORS Configuration
const string CorsPolicyName = "FrontendCorsPolicy";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: CorsPolicyName, policy =>
    {
            policy.WithOrigins("http://localhost:5173")
                  .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                  .WithHeaders("Content-Type", "Authorization")
                  .SetPreflightMaxAge(TimeSpan.FromSeconds(86400));
    });
});

var app = builder.Build();

// Middleware order matters: UseRouting -> UseCors -> UseAuthentication -> UseAuthorization
app.UseRouting();
app.UseCors(CorsPolicyName);
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Preflight (OPTIONS)

Triggered · Passed

Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:5173', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

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:

DevTools Console Output

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.

  1. 1Define a Strict ASP.NET Core CORS Policy Without Trailing Slashes

    Program.cs

    Configure 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.cscsharp
    const 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();
  2. 2Trust the .NET Local HTTPS Development Certificate

    terminal

    When 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.

    terminalbash
    dotnet dev-certs https --trust
  3. 3Support Dynamic Staging Subdomains Safely Using SetIsOriginAllowed

    Program.cs

    If 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.cscsharp
    policy.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));
    });
  4. 4Call the .NET Minimal API Cleanly From React With Environment Config

    src/api/invoices.ts

    Bind 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.tstypescript
    const 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tool · Same-Origin Reverse 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).

Open Nginx Builder

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.
Browse all 12 stacks →