---
title: "How to Fix CORS Errors in ASP.NET Core and FastAPI"  
description: "Understand and fix “blocked by CORS policy” errors. What CORS is, why browsers enforce it, preflight requests, credentials and wildcards, with correct"  
author: "Nisha Modi"  
published: 2026-11-23  
canonical: https://www.mindstick.com/blog/307152/how-to-fix-cors-errors-in-asp-net-core-and-fastapi  
category: "web development"  
tags: ["fix cors error asp.net core fastapi", "asp.net core", "fastapi", "web development", "Website Performance"]  
reading_time: 6 minutes  

---

# How to Fix CORS Errors in ASP.NET Core and FastAPI

You’ve built an API. You’ve built a front end. Postman works perfectly. Then the browser shows this in red:

```
Access to fetch at 'https://api.example.com/orders' from origin 'https://app.example.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.
```

CORS errors are among the most searched web development problems, mostly because they’re misunderstood. Once you see what the browser is actually checking, the fix is usually a few lines of configuration.

## What CORS actually is

Browsers enforce a rule called the **same-origin policy**: JavaScript on one origin can’t read responses from another origin unless that other origin allows it.

An **origin** is the combination of **scheme + host + port**:

| URL | Same origin as `https://app.example.com`? |
| --- | --- |
| `https://app.example.com/orders` | Yes |
| `http://app.example.com` | No (different scheme) |
| `https://api.example.com` | No (different host) |
| `https://app.example.com:8443` | No (different port) |
| `http://localhost:4200` vs `http://localhost:5000` | No (different ports) |

**CORS (Cross-Origin Resource Sharing)** is how a server says, “Yes, I allow JavaScript from these other origins to read my responses.” It does this with HTTP response headers like `Access-Control-Allow-Origin`.

### Three things that explain most confusion

1. **CORS is enforced by the browser**, not the server. That’s why Postman, curl and server-to-server calls work fine. They don’t apply the same-origin policy.
2. **The fix is always on the server** that receives the request (the API), not in the front-end code. No setting in `fetch` or Axios can override it.
3. **CORS isn’t a security wall for your API.** It protects users’ browsers from malicious sites reading data with their cookies. Your API still needs proper authentication and authorisation.

## Preflight requests

For “simple” requests (GET or POST with basic content types and no custom headers), the browser sends the request and checks the response headers.

For anything else, such as `PUT`, `DELETE`, `Content-Type: application/json`, or an `Authorization` header, the browser first sends an **OPTIONS preflight** request asking permission:

```
OPTIONS /orders
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, authorization
```

The server must answer with matching `Access-Control-Allow-*` headers. If the preflight fails, the real request is never sent. Many CORS problems are really **preflight problems**: something in the pipeline (authentication, a firewall, IIS) rejects the OPTIONS request before CORS middleware can answer it.

## Fixing CORS in ASP.NET Core

```
var builder = WebApplication.CreateBuilder(args);

var allowedOrigins = builder.Configuration
    .GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();

builder.Services.AddCors(options =>
{
    options.AddPolicy("Frontend", policy =>
    {
        policy.WithOrigins(allowedOrigins)          // exact origins, no trailing slash
              .WithMethods("GET", "POST", "PUT", "DELETE")
              .WithHeaders("Content-Type", "Authorization")
              .AllowCredentials()                    // only if you use cookies
              .SetPreflightMaxAge(TimeSpan.FromHours(1));
    });
});

builder.Services.AddAuthentication(/* ... */);
builder.Services.AddAuthorization();
builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("Frontend");      // after UseRouting, before auth
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();
```

`appsettings.json`:

```
{
  "Cors": {
    "AllowedOrigins": [ "https://app.example.com", "http://localhost:4200" ]
  }
}
```

Keep development origins like `localhost` in `appsettings.Development.json` so they don’t end up allowed in production.

### ASP.NET Core gotchas

- **Middleware order matters.** `UseCors` must come after `UseRouting` and **before** `UseAuthentication`, `UseAuthorization` and endpoint mapping. Otherwise authorisation can reject the preflight with a 401 before CORS headers are added.
- **No trailing slash.** `https://app.example.com/` won’t match the browser’s origin `https://app.example.com`.
- **`AllowAnyOrigin()`** **can’t be combined with** **`AllowCredentials()`****.** The CORS specification forbids a wildcard origin with credentials, and ASP.NET Core throws an error if you try.
- **Errors can hide CORS headers.** If your endpoint throws an unhandled exception, the error response may not include CORS headers, so the browser reports a CORS error instead of the real 500. Check the server logs or the Network tab’s response status.
- **Per-endpoint control:** use `.RequireCors("Frontend")` on endpoints or `[EnableCors("Frontend")]` on controllers if only some endpoints should be cross-origin.

## Fixing CORS in FastAPI

```
import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

allowed_origins = os.environ.get(
    "ALLOWED_ORIGINS", "https://app.example.com,http://localhost:5173"
).split(",")

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,     # exact origins
    allow_credentials=True,            # only if you use cookies
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Content-Type", "Authorization"],
    max_age=3600,
)

@app.get("/orders")
def orders():
    return [{"id": 1042, "status": "shipped"}]
```

### FastAPI gotchas

- **Add the middleware once, at app level**, so it wraps every route, including error responses.
- **`allow_origins=["*"]`** **with** **`allow_credentials=True`** doesn’t work as people expect: browsers reject a wildcard origin when credentials are included. List exact origins instead.
- **Subdomains:** use `allow_origin_regex=r"https://.*\.example\.com"` carefully, making sure the pattern can’t match attacker-controlled domains like `example.com.evil.net`.

## Credentials: cookies and auth headers

If your front end sends **cookies** (`fetch(url, { credentials: "include" })` or Axios `withCredentials: true`):

- the server must return `Access-Control-Allow-Credentials: true`
- `Access-Control-Allow-Origin` must be the **exact** origin, not `*`
- cookies for cross-site requests need `SameSite=None; Secure`

If you use **bearer tokens** in the `Authorization` header and no cookies, you don’t need `AllowCredentials`, but you do need to allow the `Authorization` header.

## Server and proxy pitfalls

**IIS:** The **WebDAV module** can intercept `OPTIONS` (and `PUT`/`DELETE`) requests. If preflights fail on IIS but work locally, remove WebDAV for your site, or ensure the ASP.NET Core Module handles OPTIONS. Also avoid adding CORS headers in **both** `web.config` and your app. Duplicate `Access-Control-Allow-Origin` headers cause browsers to reject the response.

**Nginx, API gateways and CDNs:** Make sure they pass OPTIONS requests through, or handle CORS consistently in one place. Again, configure CORS in **one** layer only.

**Windows Authentication:** Preflight requests don’t carry credentials. If anonymous access is disabled, IIS returns 401 to the preflight. Allow anonymous OPTIONS requests, or use the IIS CORS Module, which handles preflights before authentication.

## A debugging checklist

Open DevTools → **Network**, reproduce the problem, and check:

1. **Is there an OPTIONS request?** What status did it get? A 401, 404 or 405 points to authentication, routing or WebDAV, not CORS settings.
2. **What’s the** **`Origin`** **header** the browser sent? Does it exactly match your allowed list?
3. **What** **`Access-Control-Allow-*`** **headers** came back? Are any missing or duplicated?
4. **Did the actual request fail with a 500?** Check server logs; the CORS message may be hiding a server error.
5. **Are credentials involved?** Then wildcard origins won’t work.

## Do you even need CORS?

Sometimes the cleanest fix is avoiding cross-origin requests altogether:

- **Serve the front end and API from the same origin**, for example `https://example.com` and `https://example.com/api`, using a reverse proxy.
- **Use your dev server’s proxy** during development (Vite, Angular CLI and others support proxying `/api` to your back end), so the browser only talks to one origin.

## The fix in one paragraph

A CORS error means the browser didn’t get permission from the API to share its response with your front end’s origin. Fix it on the **server**: list exact allowed origins, allow the methods and headers you use, put the CORS middleware in the right place, and make sure OPTIONS preflight requests aren’t blocked by authentication, WebDAV or a proxy.

Avoid `*` in production, never combine wildcards with credentials, and configure CORS in one layer only. Do that, and the red error disappears for good.

---

Original Source: https://www.mindstick.com/blog/307152/how-to-fix-cors-errors-in-asp-net-core-and-fastapi

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
