🌐 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

Popular posts from this blog

Scrutor the built-in Dependency Injection (DI)

πŸ”Œ Extension Methods in C#: Power Up Your Code Without Modifying It

πŸ§… Understanding the Onion Architecture: A Clean Approach to Building Scalable Applications

Understanding Dependency Injection: A Modern Guide for Developers

πŸ” JWT (JSON Web Token) Explained: Secure Your APIs the Modern Way

πŸ›‘️ SIEM Logs Explained: How to Build Secure and Auditable .NET Apps

Ensuring Data Integrity: The Backbone of Reliable Systems

πŸ—‚️ DROP vs DELETE vs TRUNCATE in SQL: What’s the Difference?

πŸ”— SQL JOINs Explained: Mastering Table Relationships