ASP.NET Core  

How to Fix CORS Error in ASP.NET Core Web API?

Introduction

A CORS error in an ASP.NET Core Web API usually happens when a frontend application such as Angular, React, or a mobile app tries to call your API from a different domain, port, or protocol. Browsers block these requests by default for security reasons. This behavior is known as Cross-Origin Resource Sharing (CORS). If CORS is not configured correctly in your ASP.NET Core Web API, the browser will prevent the request and display a CORS policy error.

This guide explains in simple words how to fix CORS errors in ASP.NET Core Web API and configure cross-origin requests properly for development and production environments.

What Causes a CORS Error?

A CORS error happens when:

  • Your frontend runs on http://localhost:4200

  • Your ASP.NET Core Web API runs on https://localhost:5001

  • The API does not explicitly allow that origin

Since the protocol, domain, or port is different, the browser treats it as a cross-origin request. If the server does not return the correct CORS headers, the request is blocked.

Common CORS error message:

"Access to fetch at 'API_URL' from origin 'FRONTEND_URL' has been blocked by CORS policy."

Step 1: Enable CORS in Program.cs

To fix the CORS issue, you must configure CORS in your ASP.NET Core Web API.

Add CORS services in Program.cs:

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

This allows requests from your frontend origin.

Step 2: Add CORS Middleware in Correct Order

After registering CORS, you must enable it in the middleware pipeline.

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

Important: UseCors() must be placed before UseAuthorization() and before MapControllers(). Incorrect middleware order is a common reason why CORS configuration does not work.

Step 3: Allow Multiple Origins (If Needed)

If your application has multiple frontend environments such as development and production:

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

Avoid using AllowAnyOrigin() in production unless your API is public.

Step 4: Fix CORS for Authentication (Cookies or JWT)

If you are using cookies or authentication tokens, you may need to allow credentials.

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

Important rule:

  • You cannot use AllowAnyOrigin() together with AllowCredentials().

For secure enterprise ASP.NET Core Web API applications, always specify exact frontend domains.

Step 5: Handle Preflight (OPTIONS) Requests

For PUT, DELETE, or custom header requests, browsers send a preflight OPTIONS request before the actual API call.

If CORS is configured correctly with AllowAnyHeader() and AllowAnyMethod(), ASP.NET Core automatically handles preflight requests.

If you still see issues, check:

  • Correct HTTP methods are allowed

  • Headers are permitted

  • The frontend request matches allowed origin exactly (including port)

Step 6: Fix CORS in Development Using Proxy (Optional)

If you are using Angular or React in development, you can configure a proxy to avoid CORS during development.

Example for Angular proxy configuration:

{
  "/api": {
    "target": "https://localhost:5001",
    "secure": false,
    "changeOrigin": true
  }
}

This helps avoid cross-origin issues during local development.

Step 7: Check HTTPS and Port Mismatch

Sometimes CORS errors happen because:

  • Frontend uses HTTP

  • API uses HTTPS

Make sure protocol and ports are correctly configured in your CORS policy.

Example:

policy.WithOrigins("https://localhost:4200");

Even a small mismatch can cause CORS failure.

Step 8: Common Mistakes That Cause CORS Errors

  • Forgetting to call UseCors()

  • Incorrect middleware order

  • Wrong origin URL (missing https or port)

  • Mixing AllowAnyOrigin() with AllowCredentials()

  • Not restarting application after configuration changes

  • Deploying without updating production CORS policy

Carefully reviewing these points usually resolves most CORS problems in ASP.NET Core Web API.

Production Best Practices for CORS in ASP.NET Core

For secure and scalable ASP.NET Core Web API applications:

  • Restrict CORS to trusted frontend domains

  • Use HTTPS only

  • Avoid wildcard origins in enterprise applications

  • Log rejected cross-origin requests

  • Test CORS behavior in staging before production deployment

Proper CORS configuration improves API security and prevents unauthorized cross-origin access.

Summary

Fixing a CORS error in ASP.NET Core Web API requires properly configuring Cross-Origin Resource Sharing in Program.cs, defining a named policy with allowed origins, enabling the CORS middleware in the correct order, and ensuring protocol and port values match exactly. Additional considerations such as handling credentials, preflight requests, HTTPS configuration, and production security settings are essential for stable and secure cross-origin communication. By following these best practices, developers can eliminate CORS errors and ensure smooth integration between frontend applications and ASP.NET Core Web APIs in cloud-native and enterprise environments.