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();

Join the conversation! Your thoughts help the community grow.