CORS & Preflight Simulator · ASP.NET Core 8/9 Web API + Angular (Port 4200)

ASP.NET Core 8/9 + Angular CORS Config Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between Angular (Port 4200) and ASP.NET Core 8/9 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 (Angular (Port 4200))

2. Server Response Policy (ASP.NET Core 8/9 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:4200")
                  .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                  .WithHeaders("Content-Type", "Authorization", "X-Correlation-Id")
                  .SetPreflightMaxAge(TimeSpan.FromSeconds(86400))
                  .AllowCredentials();
    });
});

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

HTTP method "PUT" is not a CORS-safelisted method (only GET, HEAD, and POST skip preflight). 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, X-Correlation-Id.

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:4200', 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:4200
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Correlation-Id
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (PUT)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Credentials: true
Vary: Origin

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

Typical Browser Console Error (Angular (Port 4200) → ASP.NET Core 8/9 Web API)

When cross-origin headers are missing, mismatched, or blocked during preflight between Angular (Port 4200) and ASP.NET Core 8/9 Web API, Chrome and Firefox log an error matching the pattern below in DevTools:

DevTools Console Output

Access to XMLHttpRequest at 'https://localhost:7142/api/customers/12' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Why CORS Blocks Requests Between Angular (Port 4200) and ASP.NET Core 8/9 Web API

Enterprise full-stack teams regularly pair an ASP.NET Core 8 or 9 Web API (running on Kestrel at https://localhost:7142 or http://localhost:5142) with an Angular CLI single-page application running on http://localhost:4200. Even though ASP.NET Core ships with a mature, first-class CORS middleware in Microsoft.AspNetCore.Cors, misordering the middleware pipeline in Program.cs or triggering an automatic HTTP-to-HTTPS redirect during OPTIONS preflights causes immediate browser rejections.

ASP.NET Core is notably stricter at startup than many dynamic web frameworks: chaining policy.AllowAnyOrigin().AllowCredentials() throws an InvalidOperationException immediately because .NET explicitly enforces the Fetch Standard prohibition on wildcard origins with credentials. Furthermore, if app.UseCors() is placed after app.UseAuthorization(), after app.UseResponseCaching(), or after custom authentication guards, unauthenticated preflights or cached responses bypass CORS header injection entirely.

Angular's HttpClient architecture makes preflight hygiene especially critical because HTTP interceptors routinely attach Authorization: Bearer tokens and observability headers like X-Correlation-Id or X-Tenant-Id to every outbound API call; forcing OPTIONS preflights even on GET requests. Combined with Kestrel's default UseHttpsRedirection() middleware, pointing Angular at an http:// URL triggers a 307 redirect on OPTIONS, which every browser immediately blocks.

For enterprise ASP.NET Core 8 and 9 Web APIs paired with Angular CLI frontends, treating CORS configuration as an audited part of your deployment pipeline eliminates environment-specific regressions across IIS, Kestrel, Docker, and Azure App Service. Always bind Cors:AllowedOrigins from appsettings or secret stores per environment, disable duplicate CORS toggles in cloud hosting portals, and verify your middleware order in Program.cs whenever introducing authentication, output caching, or rate-limiting middleware. Confirming in browser DevTools that Kestrel answers OPTIONS preflights directly with HTTP 204, without an intermediate HTTP-to-HTTPS 307 redirect, keeps Angular HttpClient interceptors fast and reliable across Chrome, Edge, Firefox, and Safari.

Step-by-Step ASP.NET Core 8/9 Web API + Angular (Port 4200) CORS Fix Guide

Follow each step below in order to eliminate preflight failures and lock down production origins safely for ASP.NET Core 8/9 Web API.

  1. 1Register a Named CORS Policy in Program.cs

    Program.cs

    Define a named CORS policy inside builder.Services.AddCors() listing your exact Angular origin (http://localhost:4200 without any trailing slash), explicit HTTP methods, custom interceptor headers like X-Correlation-Id, preflight cache duration, and AllowCredentials() whenever cookies, Windows Authentication, or SignalR negotiation are required.

    Program.cscsharp
    const string AngularCorsPolicy = "AngularFrontendPolicy";
    
    var builder = WebApplication.CreateBuilder(args);
    
    var allowedOrigins = builder.Configuration
        .GetSection("Cors:AllowedOrigins")
        .Get<string[]>() ?? ["http://localhost:4200"];
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: AngularCorsPolicy, policy =>
        {
            policy.WithOrigins(allowedOrigins)
                  .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                  .WithHeaders("Content-Type", "Authorization", "X-Correlation-Id")
                  .SetPreflightMaxAge(TimeSpan.FromSeconds(86400))
                  .AllowCredentials();
        });
    });
    
    builder.Services.AddControllers();
  2. 2Place app.UseCors() in the Exact Required Pipeline Position

    Program.cs

    ASP.NET Core middleware ordering is strictly sequential. Register app.UseCors() AFTER app.UseRouting() and strictly BEFORE app.UseAuthentication(), app.UseAuthorization(), app.UseResponseCaching(), and app.MapControllers(). Skip UseHttpsRedirection() in Development if local Angular requests target HTTP.

    Program.cscsharp
    var app = builder.Build();
    
    if (!app.Environment.IsDevelopment())
    {
        app.UseHttpsRedirection();
    }
    
    app.UseRouting();
    app.UseCors(AngularCorsPolicy);
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();
    
    app.Run();
  3. 3Externalize Allowed Origins Per Environment in appsettings.json

    appsettings.Development.json

    Store allowed Angular origins in environment-specific JSON settings or container environment variables (Cors__AllowedOrigins__0) so production deployments never accidentally retain http://localhost:4200 in their allowlist.

    appsettings.Development.jsonjson
    {
      "Cors": {
        "AllowedOrigins": [
          "http://localhost:4200"
        ]
      }
    }
  4. 4Configure Angular HttpClient and Environment Base URL

    src/app/services/customer.service.ts

    Point Angular directly at the HTTPS Kestrel endpoint (https://localhost:7142) instead of the HTTP port that 307-redirects to HTTPS, and enable withCredentials: true only when your ASP.NET Core policy calls AllowCredentials() for cookies or SignalR.

    src/app/services/customer.service.tstypescript
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Injectable, inject } from '@angular/core';
    
    @Injectable({ providedIn: 'root' })
    export class CustomerService {
      private readonly http = inject(HttpClient);
      private readonly apiBase = 'https://localhost:7142/api';
    
      updateCustomer(id: number, payload: { name: string }, token: string) {
        const headers = new HttpHeaders({
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
          'X-Correlation-Id': crypto.randomUUID(),
        });
    
        return this.http.put(`${this.apiBase}/customers/${id}`, payload, {
          headers,
          withCredentials: true,
        });
      }
    }

Common ASP.NET Core 8/9 Web API + Angular (Port 4200) 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

app.UseHttpsRedirection() Breaking OPTIONS Preflights With HTTP 307

If Angular calls http://localhost:5142/api/customers while UseHttpsRedirection() is active, ASP.NET Core returns a 307 redirect to https://localhost:7142 on the OPTIONS preflight. Browsers strictly reject redirects on preflight requests; always target the HTTPS endpoint directly or disable redirection in Development.

Pitfall 2

Calling UseCors() After UseAuthorization() or UseResponseCaching()

If app.UseAuthorization() executes before app.UseCors(), unauthenticated OPTIONS preflight requests get rejected with 401 Unauthorized before the CORS middleware ever runs. Always keep UseCors() ahead of Authentication, Authorization, and Response Caching.

Pitfall 3

IIS / Azure App Service Duplicate CORS Configuration

Enabling CORS in both the Azure App Service Portal (or IIS web.config) AND ASP.NET Core Program.cs causes duplicate Access-Control-Allow-Origin headers or overrides your ASP.NET Core policy completely. Configure CORS in one layer only; prefer Program.cs for full code-level control and versioned audits.

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

Why does ASP.NET Core throw an exception when I chain AllowAnyOrigin() and AllowCredentials()?
The Fetch Standard forbids combining wildcard * origin with Access-Control-Allow-Credentials: true. ASP.NET Core validates this rule at startup and throws InvalidOperationException to prevent silent browser failures. Use WithOrigins("http://localhost:4200").AllowCredentials() instead.
Can I use Angular proxy.conf.json instead of ASP.NET Core CORS?
Angular's ng serve --proxy-config proxy.conf.json avoids CORS locally by forwarding /api through port 4200. However, if your production Angular bundle is hosted on Azure Static Web Apps, CloudFront, or a separate origin from your ASP.NET Core API, you must still configure AddCors and UseCors accurately.
How do I allow SignalR hubs to work with Angular across origins?
SignalR browser clients send credentialed negotiate requests by default. Your ASP.NET Core CORS policy must use WithOrigins(..) (never AllowAnyOrigin()), allow SignalR headers (x-requested-with and x-signalr-user-agent), and chain AllowCredentials().
Why does Angular get a CORS error when ASP.NET Core throws an unhandled exception?
If UseExceptionHandler() runs before UseCors() and clears response headers while re-executing an error endpoint, Access-Control-Allow-Origin headers can be stripped. Keep app.UseCors() properly ordered and ensure custom exception middleware preserves CORS headers on 500 ProblemDetails responses.
Browse all 12 stacks →