How to Configure CORS in ASP.NET Core

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web applications from making requests to a domain different from the one that served the application. In ASP.NET Core, CORS is handled server-side through built-in dependency injection services and middleware. This guide covers how to define CORS policies, enable the middleware in your application pipeline, and apply these rules either globally or to specific endpoints using C#.

1. Register CORS Services

To use CORS in ASP.NET Core, you must first register the CORS services in your application's dependency injection container within Program.cs. You can define one or more named policies or set a default policy.

var builder = WebApplication.CreateBuilder(args);

// Define a policy name
var myAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: myAllowSpecificOrigins,
        policy =>
        {
            policy.WithOrigins("https://example.com", "https://app.example.com")
                  .WithMethods("GET", "POST", "PUT", "DELETE")
                  .WithHeaders("Content-Type", "Authorization")
                  .AllowCredentials();
        });

    // Alternatively, define a default policy
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("https://trusteddomain.com")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

builder.Services.AddControllers();

2. Add CORS Middleware to the Pipeline

Add the CORS middleware to the request processing pipeline using app.UseCors(). The order of middleware execution is critical:

  • Place app.UseCors() after app.UseRouting().
  • Place app.UseCors() before app.UseAuthentication() and app.UseAuthorization().
var app = builder.Build();

app.UseHttpsRedirection();
app.UseRouting();

// Enable CORS
app.UseCors(myAllowSpecificOrigins);

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

If you configured a default policy using AddDefaultPolicy, calling app.UseCors() without arguments will apply that default policy.

3. Apply CORS Policies to Controllers and Endpoints

Instead of applying a policy globally via the middleware, you can control CORS rules on a per-controller, per-action, or per-endpoint basis.

Controller-Based APIs

Use the [EnableCors] and [DisableCors] attributes to apply or bypass policies at the controller or action level:

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
[EnableCors("_myAllowSpecificOrigins")]
public class UsersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetUsers()
    {
        return Ok(new[] { "User1", "User2" });
    }

    [HttpGet("public")]
    [DisableCors]
    public IActionResult GetPublicInfo()
    {
        return Ok("No CORS restrictions applied.");
    }
}

Minimal APIs

For Minimal APIs, chain the .RequireCors() method directly onto route definitions:

app.MapGet("/api/data", () => Results.Ok(new { Data = "Sample Content" }))
   .RequireCors(myAllowSpecificOrigins);

4. Security Considerations

  • Avoid AllowAnyOrigin() with AllowCredentials(): The CORS specification does not permit wildcard origins (*) when credentials (such as cookies or HTTP authentication headers) are allowed. ASP.NET Core will throw an exception at runtime if both are configured together.
  • Specify exact methods and headers: While AllowAnyMethod() and AllowAnyHeader() are useful during development, explicitly list the allowed HTTP verbs and headers in production to minimize attack surfaces.
  • CORS is not an authorization mechanism: CORS only instructs compliant browsers whether to share responses with frontend scripts. It does not stop non-browser clients (such as Postman, cURL, or malicious scripts) from sending requests directly to your server. Always implement proper authentication and authorization.