π CORS in .NET Explained: Solving the Cross-Origin Problem Like a Pro
Have you ever seen this error?
Access to fetch at 'http://api.example.com/data'
from origin 'http://localhost:4200' has been blocked by CORS policy
π
Frustrating, right? Don’t worry — it’s a CORS issue, and in this post,
we’ll break it down and solve it.
π§ What is CORS?
CORS (Cross-Origin Resource Sharing) is a browser security feature that
controls how web pages can make requests to a different domain than the
one that served the web page.
π Same-Origin Policy
Browsers follow the Same-Origin Policy,
which means:
- A frontend running on http://localhost:3000
- Cannot make API calls to http://api.mysite.com (a different
origin)
- Unless the server allows it via CORS
headers
π§Ύ CORS in Real Life
Imagine your Angular app runs at:
http://localhost:4200
And your .NET Core Web API runs at:
http://localhost:5000
By default, if you try to call the API from the
frontend, the browser will block the request unless the server
explicitly allows it.
⚙️
How to Enable CORS in ASP.NET Core
✅
Step 1: Add CORS Services in Program.cs
csharp
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontendApp",
policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
✅
Step 2: Use the CORS Policy
csharp
var app = builder.Build();
app.UseCors("AllowFrontendApp");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
π
Always call UseCors() before UseAuthorization() and MapControllers().
π§ͺ Common CORS Configurations
π Allow Any Origin (Not recommended for production)
csharp
policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
π Restrict by Origin
csharp
policy.WithOrigins("https://myapp.com");
π Allow Credentials (cookies, auth headers)
csharp
policy.WithOrigins("https://myapp.com")
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
⚠️ You cannot
use AllowAnyOrigin() with AllowCredentials() — it’s a security risk.
π§° Testing CORS
Use browser dev tools (F12) → Network
tab to inspect preflight (OPTIONS) requests and responses.
Look for headers like:
- Access-Control-Allow-Origin
- Access-Control-Allow-Methods
- Access-Control-Allow-Headers
π§― Common CORS Errors & Fixes
Error |
Cause |
Fix |
Blocked by CORS policy |
Server didn’t send Access-Control-Allow-Origin |
Add CORS policy in backend |
No 'Access-Control-Allow-Origin' header |
Origin not allowed |
Use .WithOrigins("your frontend
URL") |
The value of the
'Access-Control-Allow-Origin' header is '*' |
You're using AllowCredentials() |
Don’t mix AllowAnyOrigin() with AllowCredentials() |
π§© Bonus: CORS in .NET Minimal APIs
If you're using minimal APIs:
csharp
app.UseCors(policy =>
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod());
Or:
csharp
app.MapGet("/hello", () => "Hi").RequireCors("AllowFrontendApp");
π Summary
✅ CORS is
a browser feature that prevents unsafe cross-origin requests
✅ Your backend must explicitly allow the frontend origin
✅ In .NET, use AddCors() and UseCors() to configure
✅ Keep security in mind — never allow all origins in production
Comments
Post a Comment