Introduction

In modern web development using ASP.NET Core Web API, your frontend and backend almost never run on the same origin. For example, your React or Angular application might be running on http://localhost:3000 during development, while your API is hosted on a different domain like https://api.yourapp.com.

By default, browsers block such cross-origin requests due to a security rule called the Same-Origin Policy. This is where CORS (Cross-Origin Resource Sharing) becomes essential.

CORS allows your ASP.NET Core backend to explicitly define which external domains (origins) are allowed to access your API, making your application both secure and functional.

In this detailed guide, you will learn:

What is CORS?

CORS (Cross-Origin Resource Sharing) is a browser-enforced security mechanism that controls how resources on a web server can be requested from another domain.

Real-Life Analogy

Think of your API as a secure office building:

Similarly, CORS policies define which domains can access your backend.

Why CORS is Important in Real Applications

In real-world systems:

Without CORS:

With CORS:

Real-World Scenario

Consider an e-commerce platform:

You must allow only trusted domains to access your API, not the entire internet.

Step 1: Create ASP.NET Core Web API Project

dotnet new webapi -n CorsDemo

Step 2: Configure CORS Policy for Multiple Origins

In Program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins", policy =>
    {
        policy.WithOrigins(
            "http://localhost:3000",
            "https://myfrontend.com"
        )
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
});

Deep Explanation

Step 3: Apply CORS Middleware

app.UseCors("AllowSpecificOrigins");

This must be placed before authorization middleware:

app.UseAuthorization();

Step 4: Apply CORS at Controller Level (Optional)

[EnableCors("AllowSpecificOrigins")]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("CORS Enabled Response");
    }
}

Step 5: Testing CORS Behavior

How CORS Works Internally (Important Concept)

When a browser makes a cross-origin request:

  1. It sends a preflight request (OPTIONS)

  2. Server responds with allowed origins, headers, and methods

  3. Browser validates response

  4. If allowed → actual request is sent

This is why proper configuration is critical.

Real-World Use Case

Scenario: Multi-Frontend Architecture

CORS setup:

policy.WithOrigins(
    "https://app.company.com",
    "https://admin.company.com"
);

This ensures only trusted clients can access backend services.

Before vs After CORS Configuration

Before:

After:

Common Mistakes Developers Make

Mistake 1: Using AllowAnyOrigin in Production

policy.AllowAnyOrigin();

This exposes your API to any domain and is a major security risk.

Mistake 2: Incorrect Middleware Order

CORS must be configured before authentication/authorization middleware.

Mistake 3: Using Credentials with AllowAnyOrigin

This combination is not allowed and causes runtime errors.

Advanced CORS Configuration

Allow Credentials (Cookies / Auth Tokens)

policy.WithOrigins("https://myfrontend.com")
      .AllowCredentials()
      .AllowAnyHeader()
      .AllowAnyMethod();

Restrict HTTP Methods

policy.WithMethods("GET", "POST");

Advantages of CORS in ASP.NET Core

Disadvantages of CORS

Best Practices for CORS Configuration

Summary

CORS configuration in ASP.NET Core is a fundamental requirement for modern distributed web applications where frontend and backend operate on different domains. By properly defining policies for multiple origins, controlling headers and HTTP methods, and understanding how browsers enforce CORS, developers can build secure and scalable APIs. Whether you are working on enterprise systems, microservices, or cloud-based applications, implementing CORS correctly ensures seamless communication while protecting your backend from unauthorized access.