How to Fix CORS Errors in ASP.NET Core 10 Web API with React and Angular
If your React or Angular app reports a CORS error against an ASP.NET Core 10 Web API, open the browser’s Network panel and inspect the failing request before changing the policy. Find the exact frontend origin, then check whether the browser sent an OPTIONS preflight. Register an explicit origin allowlist with AddCors and apply it with UseCors after routing and before authorization. Verify the headers on the preflight and on the actual response.
A common reproduction is a React development server on port 5173 calling a .NET API on port 5080. A basic GET works. Then a JSON POST fails and the API action never runs. Those two requests exercise different browser behavior. The GET can go straight to the API, while the JSON POST normally starts with a preflight.
In this guide: Read the failure · Configure ASP.NET Core · Call from React · Call from Angular · Test the policy · Cookies and bearer tokens · Troubleshooting · FAQ
Read the failure
An origin consists of a scheme, host, and port. http://localhost:5173, http://127.0.0.1:5173, and https://localhost:5173 are three different origins. The browser sends the page’s origin in its Origin header. The API’s hostname belongs in the request URL. There is no path or trailing slash in the origin.
Cross-Origin Resource Sharing (CORS) lets a server tell browsers which origins can read cross-origin responses. For requests that need a preflight, the browser also asks whether the proposed method and request headers are allowed. A JSON POST usually needs a preflight because application/json is outside the CORS-safelisted content types. Sending Authorization also triggers preflight. A preflight sends header names such as authorization, without sending the bearer token itself.
- Open DevTools → Network, enable Preserve log if navigation is involved, and retry once.
- If an
OPTIONSentry exists, compare itsOrigin,Access-Control-Request-Method, andAccess-Control-Request-Headerswith the response. - If the actual request appears, check its status and CORS headers separately. An API action can succeed while the browser refuses to expose its response. A server error can also appear as a CORS failure when an upstream layer generated a response without CORS headers.
For the protocol rules, see MDN’s CORS guide and Microsoft’s ASP.NET Core 10 CORS documentation.
Configure ASP.NET Core
Install the .NET 10 SDK and create a minimal Web API. The Web SDK includes the ASP.NET Core CORS middleware.
dotnet new web -n CorsLab -f net10.0
cd CorsLabReplace Program.cs with the following. This is a local echo endpoint for diagnosing the request path. It stores no notes. The allowed Authorization header demonstrates the CORS setting for bearer clients. Add your API’s own authentication before using such a header to protect resources.
var builder = WebApplication.CreateBuilder(args);
const string policyName = "BrowserClients";
var origins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>();
if ((origins is null || origins.Length == 0) && builder.Environment.IsDevelopment())
{
origins = ["http://localhost:5173", "http://localhost:4200"];
}
if (origins is null || origins.Length == 0 ||
origins.Any(origin => !Uri.TryCreate(origin, UriKind.Absolute, out var uri) ||
(uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ||
origin != uri.GetLeftPart(UriPartial.Authority) ||
(!builder.Environment.IsDevelopment() && uri.Scheme != Uri.UriSchemeHttps)))
{
throw new InvalidOperationException("Set Cors:Origins to explicit origins without paths or trailing slashes.");
}
builder.Services.AddCors(options => options.AddPolicy(policyName, policy => policy
.WithOrigins(origins)
.WithMethods("GET", "POST")
.WithHeaders("Content-Type", "Authorization")
.WithExposedHeaders("X-Request-Id")));
var app = builder.Build();
app.UseRouting();
app.UseCors(policyName);
app.MapGet("/api/notes", () => new[] { new Note("Check the preflight first") });
app.MapPost("/api/notes", (Note note, HttpContext context) =>
{
context.Response.Headers["X-Request-Id"] = context.TraceIdentifier;
if (string.IsNullOrWhiteSpace(note.Text))
{
return Results.BadRequest(new { error = "Text is required." });
}
return Results.Ok(note);
});
app.Run();
public sealed record Note(string? Text);Start the lab on loopback with an explicit port. In PowerShell, set the environment using $env:ASPNETCORE_ENVIRONMENT = 'Development' and then run the dotnet run portion separately.
ASPNETCORE_ENVIRONMENT=Development dotnet run --no-launch-profile --urls http://localhost:5080Use the named policy on all browser-facing endpoints in this small API. With authentication and authorization installed in a real app, the order is routing → CORS → authentication → authorization. A matching global policy lets the middleware handle preflight automatically. Registering the policy alone has no effect until the pipeline applies it. Mixing global middleware and endpoint-specific policies makes it harder to determine which policy handled the request.
The lab uses development defaults only in Development. In production, set environment variables such as Cors__Origins__0=https://app.example.com and Cors__Origins__1=https://admin.example.com for the sites you operate. Missing or invalid origins fail startup. Use the API’s final HTTPS URL from browser clients. An HTTP-to-HTTPS redirect in the preflight path can cause a browser failure, even if navigating to the URL manually seems fine.
Call from React
Create a Vite React project with npm create vite@latest cors-react -- --template react. Inside it, run npm install, replace src/App.jsx with the code below, and start it with npm run dev -- --host localhost --port 5173 --strictPort. Open the printed localhost URL. If your toolchain uses a different port, update the API allowlist and restart it.
import { useState } from 'react'
export default function App() {
const [status, setStatus] = useState('Ready')
async function sendNote() {
setStatus('Sending…')
try {
const response = await fetch('http://localhost:5080/api/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Hello from React' }),
})
if (!response.ok) throw new Error(`API returned HTTP ${response.status}`)
const note = await response.json()
setStatus(`${note.text} · ${response.headers.get('X-Request-Id')}`)
} catch (error) {
setStatus(error instanceof Error ? error.message : 'Request failed')
}
}
return <main>
<button type="button" onClick={sendNote}>Send note</button>
<p role="status">{status}</p>
</main>
}Click Send note. DevTools should show the preflight and then the POST on a fresh attempt. The UI prints the echoed text and request ID. The request ID is a response header. WithExposedHeaders allows JavaScript to read it. WithHeaders governs which request headers the frontend may send.
Call from Angular
Create a standalone Angular app with npx @angular/cli@latest new cors-angular --defaults --skip-git --ssr=false. Replace src/main.ts with the example. Run npx ng serve --host localhost --port 4200 inside the app directory. The default generated index uses the app-root selector.
import { HttpClient, HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
@Component({
selector: 'app-root',
standalone: true,
template: `
<button type="button" (click)="send()">Send note</button>
<p role="status">{{ status() }}</p>
`,
})
class App {
private readonly http = inject(HttpClient);
readonly status = signal('Ready');
send() {
this.status.set('Sending…');
this.http.post<{ text: string }>(
'http://localhost:5080/api/notes',
{ text: 'Hello from Angular' },
{ observe: 'response' },
).subscribe({
next: response => this.status.set(
`${response.body?.text} · ${response.headers.get('X-Request-Id')}`,
),
error: (error: HttpErrorResponse) => this.status.set(
error.status === 0 ? 'Browser or network blocked the request'
: `API returned HTTP ${error.status}`,
),
});
}
}
bootstrapApplication(App, { providers: [provideHttpClient()] })
.catch(error => console.error(error));Angular serializes the object payload as JSON. observe: 'response' makes the response headers available. Angular’s status 0 can come from CORS, a network failure, or another browser-level failure. Use Network and Console to tell those cases apart. See Angular’s HttpClient request guide and provideHttpClient reference.
Test the policy
Use curl.exe in Windows PowerShell if curl resolves to an alias. This Bash command models the browser’s preflight for the React POST.
curl -i -X OPTIONS http://localhost:5080/api/notes \
-H 'Origin: http://localhost:5173' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: content-type'The lab responds with 204, Access-Control-Allow-Origin: http://localhost:5173, and allowed methods and headers covering the request. Change the origin to port 5174 and repeat. The response can still be 204 with no allow-origin header. Similarly, an allowed origin can receive headers listing the policy’s methods and headers even when those lists omit the requested method or header. Check the complete permission result, including the values, instead of treating 204 as success.
curl -i http://localhost:5080/api/notes \
-H 'Origin: http://localhost:5173' \
-H 'Content-Type: application/json' \
-d '{"text":"Check the actual response"}'Expect 200, echoed JSON, the matching allow-origin header and X-Request-Id. An empty text returns 400 with the matching CORS header so the frontend can read the error. curl and Postman let you inspect HTTP responses regardless of browser CORS enforcement. Run the same request from the frontend’s actual browser origin as the final check.
Cookies and bearer tokens
A bearer-token client sets the Authorization request header. Keep it in the allowed request-header list and test preflight with authorization in the requested headers. The token is validated on the actual request. If Network shows a readable 401 or 403, debug token validation or authorization next. See the ASP.NET PB JWT authentication guide.
For cross-origin cookie authentication, the client opts in with Fetch credentials: 'include' or Angular withCredentials: true. The corresponding ASP.NET Core policy needs AllowCredentials() and explicit trusted origins. Cookie delivery also depends on scope, security attributes, and browser privacy controls. When a cookie truly needs cross-site delivery, SameSite=None requires Secure. Different ports can make requests cross-origin while remaining same-site, so assess both concepts separately.
Protect state-changing cookie-authenticated endpoints with an appropriate antiforgery design and validate the token server-side. If the client sends the token in a custom header, include that header in the allowlist. See ASP.NET Core antiforgery guidance and MDN’s credentialed CORS reference.
Troubleshooting
| Network evidence | Likely fault | Next check |
|---|---|---|
| No HTTP response, certificate warning, or mixed-content error | Transport or browser security | Verify the API is listening and its HTTPS certificate is trusted. An HTTPS frontend should use the HTTPS API. |
OPTIONS returns 301, 307, or 308 |
Redirect at proxy or app | Check Location. Call the final HTTPS endpoint directly and inspect proxy forwarding if the redirect persists. |
OPTIONS returns 401, 403, or 405 |
Auth or method filtering intercepted preflight | Check gateway and IIS logs as well as middleware order. Preserve authentication on the actual protected endpoint. |
OPTIONS returns 204, with missing or wrong allow-origin |
Wrong origin or policy | Copy Origin verbatim from DevTools, check the active environment and verify which component generated the response. |
| Allow-origin is correct but POST is absent | Method policy | Check Access-Control-Allow-Methods against the requested method. |
| Allow-origin is correct but authorization is absent | Header policy | Check Access-Control-Allow-Headers against the browser’s requested header names. |
POST shows 500 and missing CORS headers |
An intermediary or exception path produced a response | Find the request in proxy and application logs. Start with the server-side error and inspect headers at each hop. |
| Two allow-origin values or one comma-separated list | Multiple layers set the header | Choose one owner for CORS and verify the final response at the browser-facing URL. |
| GET is readable but the request ID is missing in JavaScript | Response header exposure | Check Access-Control-Expose-Headers and confirm the endpoint actually sets X-Request-Id. |
Behind a CDN or reverse proxy, compare the direct API response and the public endpoint using the same origin, method, and header names. Preserve Vary: Origin where a response varies by origin. Review gateway caching of preflights separately because the proposed method and request headers can also affect the permission decision. Avoid reflecting arbitrary origins, disabling browser protections, or setting mode: 'no-cors' to try to read a JSON response.
For adjacent issues, see deploying ASP.NET Core to IIS and global exception handling in ASP.NET Core.
FAQ
Why does GET work but POST fail? A simple GET may skip preflight. A JSON POST typically preflights because of its content type. Inspect the POST’s OPTIONS exchange first.
Should I add an OPTIONS controller action? A named CORS policy applied globally through middleware usually handles it. First check whether the preflight reaches the application and whether that policy applies.
Can I add Access-Control-Allow-Origin in React or Angular? The API or its trusted gateway sends that response header. Adding it to the browser’s request can introduce another header that the preflight must allow.
Why does a dev proxy make the problem disappear? When the browser calls its own frontend origin and the development server proxies to the API, the browser sees a same-origin request. Test the production arrangement if frontend and API are deployed at separate origins.
Does CORS prevent direct access to an API? CORS governs browser behavior. Authenticate and authorize protected endpoints independently. Keep CSRF controls where browser credentials are sent automatically.
Comments
Post a Comment