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:
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.
1Register a Named CORS Policy in Program.cs
Program.csDefine 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.cscsharpconst 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();2Place app.UseCors() in the Exact Required Pipeline Position
Program.csASP.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.cscsharpvar app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseHttpsRedirection(); } app.UseRouting(); app.UseCors(AngularCorsPolicy); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();3Externalize Allowed Origins Per Environment in appsettings.json
appsettings.Development.jsonStore 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" ] } }4Configure Angular HttpClient and Environment Base URL
src/app/services/customer.service.tsPoint 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.tstypescriptimport { 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.
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.
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.
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.
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
- 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.
Related CORS Stack Simulators
Browse all 12 stacks →ASP.NET Core Web API + React CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between ASP.NET Core 8/9 Web API and React (Vite/CRA). Debug Minimal APIs, Dev Certs, exposed headers, and cookies.
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.
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.
Nginx Reverse Proxy + Docker API CORS Simulator & Fix Guide
Fix Nginx reverse proxy CORS bugs for Docker APIs. Prevent duplicate Access-Control-Allow-Origin headers, add always on 4xx/5xx errors, and handle OPTIONS 204.