Configuring CORS in ASP.NET Core Applications Print

  • 0

What is CORS?

Cross-Origin Resource Sharing (CORS) allows your API to accept requests from different domains. Without proper CORS configuration, browsers block requests from other origins.

Common CORS Error

Access to XMLHttpRequest at 'https://api.example.com' from origin 'https://webapp.example.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present.

Basic CORS Configuration (.NET 6+)

var builder = WebApplication.CreateBuilder(args);

// Add CORS services
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("https://yourfrontend.com")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

builder.Services.AddControllers();

var app = builder.Build();

// Enable CORS - MUST be before UseAuthorization
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();

Allow Multiple Origins

policy.WithOrigins(
    "https://app1.example.com",
    "https://app2.example.com",
    "https://localhost:3000"  // For development
);

Allow All Origins (Development Only)

policy.AllowAnyOrigin()
      .AllowAnyHeader()
      .AllowAnyMethod();

Warning: Never use AllowAnyOrigin in production!

Named Policies

builder.Services.AddCors(options =>
{
    options.AddPolicy("ApiPolicy", policy =>
    {
        policy.WithOrigins("https://myapp.com")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

// Apply to specific controller
[EnableCors("ApiPolicy")]
[ApiController]
public class DataController : ControllerBase { }

Allow Credentials

For cookies or authentication headers:

policy.WithOrigins("https://myapp.com")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials();  // Cannot use with AllowAnyOrigin

CORS with Blazor WebAssembly

When your Blazor WASM app calls an API on a different domain:

  • Configure CORS on the API server (not the Blazor app)
  • Include the Blazor app origin in allowed origins

Troubleshooting

  • Order matters: UseCors() must come before UseAuthorization()
  • Check preflight: Browser sends OPTIONS request first
  • Credentials + AnyOrigin: Not allowed together
  • HTTPS required: Credentials require secure connection

Was this answer helpful?

« Back