ASP.NET Core  

How to Enable CORS in ASP.NET Core Properly?

Enabling CORS (Cross-Origin Resource Sharing) in ASP.NET Core is essential when your backend API is accessed from a different domain, port, or protocol than the frontend application. Modern web applications commonly separate the frontend (Angular, React, Vue) and backend (ASP.NET Core Web API), which makes proper CORS configuration critical for secure and seamless cross-origin communication. Incorrect CORS setup can either block legitimate requests or introduce security vulnerabilities.

What is CORS and Why It Matters

CORS is a browser security mechanism that restricts web pages from making requests to a different origin unless explicitly allowed by the server. An origin consists of:

  • Protocol (HTTP or HTTPS)

  • Domain

  • Port

If any of these differ, the browser treats it as a cross-origin request.

In ASP.NET Core Web API applications, CORS must be configured correctly to allow trusted frontend applications to access backend resources without exposing APIs to unauthorized domains.

Common CORS Scenarios in ASP.NET Core

Typical use cases include:

  • Angular frontend running on http://localhost:4200 accessing ASP.NET Core API on https://localhost:5001

  • React SPA hosted on a different domain

  • Microservices communicating across subdomains

  • Cloud-hosted frontend and backend deployed separately

Without proper CORS configuration, the browser blocks these requests before they even reach the API logic.

Step 1: Register CORS Services

In ASP.NET Core, CORS must be added to the service container in Program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontendApp", policy =>
    {
        policy.WithOrigins("http://localhost:4200")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

This defines a named policy that allows requests from a specific origin.

Step 2: Enable CORS Middleware

After registering the policy, enable it in the middleware pipeline:

app.UseCors("AllowFrontendApp");

Important: Place UseCors before UseAuthorization and before mapping controllers to ensure the policy is applied correctly.

app.UseCors("AllowFrontendApp");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Middleware order is critical in ASP.NET Core request processing.

Allowing Multiple Origins

If multiple frontend applications need access:

policy.WithOrigins(
    "http://localhost:4200",
    "https://myfrontend.com"
)
.AllowAnyHeader()
.AllowAnyMethod();

Avoid using AllowAnyOrigin in production unless the API is intentionally public.

Allowing Credentials (Cookies or JWT Tokens)

When authentication cookies or credentials are involved:

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

Important rules:

  • AllowCredentials cannot be used with AllowAnyOrigin.

  • Always specify explicit origins when credentials are enabled.

This is crucial for secure authentication flows between frontend and ASP.NET Core backend.

Using CORS at Controller Level

You can apply CORS selectively using attributes:

[EnableCors("AllowFrontendApp")]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
}

Or disable CORS for specific endpoints:

[DisableCors]

This provides granular control over API exposure.

Development vs Production CORS Strategy

Development:

  • Allow localhost origins

  • Use proxy configuration if needed

  • Keep configuration flexible

Production:

  • Restrict to exact frontend domains

  • Enforce HTTPS only

  • Avoid wildcard origins

  • Log rejected requests for monitoring

A strict production CORS policy significantly improves API security posture.

Handling Preflight Requests

For complex HTTP requests (PUT, DELETE, custom headers), browsers send a preflight OPTIONS request before the actual call.

ASP.NET Core handles preflight automatically when CORS is configured properly. If you see errors:

  • Ensure AllowAnyHeader or specific headers are configured

  • Confirm AllowAnyMethod or required HTTP verbs are permitted

  • Verify middleware order

Proper configuration ensures smooth preflight validation.

Common CORS Mistakes

  • Calling UseCors after MapControllers

  • Mixing AllowAnyOrigin with AllowCredentials

  • Forgetting HTTPS alignment between frontend and backend

  • Not matching exact origin including port

  • Using overly permissive policies in production

Understanding these pitfalls helps prevent unnecessary debugging cycles.

Testing CORS Configuration

You can verify CORS behavior using:

  • Browser Developer Tools (Network tab)

  • Postman (for API functionality testing)

  • Curl commands

Remember, CORS is enforced by browsers, not by server-to-server requests.

Summary

Properly enabling CORS in ASP.NET Core ensures secure and controlled cross-origin communication between frontend applications and backend APIs. By defining named policies, configuring middleware in the correct order, restricting allowed origins in production, and carefully handling credentials and preflight requests, developers can prevent security vulnerabilities while maintaining seamless integration across distributed web applications. A well-configured CORS strategy is fundamental to building scalable, secure, and production-ready ASP.NET Core Web APIs.