How to Enable CORS in ASP.NET Core

What is CORS?

  • Manually create the solution folder structure inside your .sln file using a text editor or Visual Studio (if possible).
  • Use the dotnet sln add command along with a workaround using Visual Studio commands (devenv) if you’re on Windows, or manually move the project in the .sln file.

How to Configure CORS in ASP.NET Core?

CORS can be configured in three simple steps:

Step 1: Add the CORS Services in Startup.cs

In the ConfigureServices method, add the CORS services and define a policy using AddCors:

Copy to clipboard
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    // Add CORS services and define a policy
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigins", builder =>
        {
            builder.WithOrigins("https://example.com", "https://another-example.com") // Allowed origins
            .AllowAnyHeader() // Allow any header
            .AllowAnyMethod(); // Allow any method (GET, POST, etc.)
        });
        options.AddPolicy("AllowAllOrigins", builder =>
        {
            builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
        });
    });
}

Step 2: Use CORS Middleware in the Pipeline

In the Configure method, apply the CORS middleware:

Copy to clipboard
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    // Use the CORS middleware
    app.UseCors("AllowSpecificOrigins"); // Use the specified policy

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Step 3: Apply CORS Policies at the Controller or Action Level

You can apply CORS at the controller or action level using the [EnableCors] attribute:

Copy to clipboard
[ApiController]
[Route("api/[controller]")]
[EnableCors("AllowSpecificOrigins")] // Apply a specific CORS policy

public class ExampleController : ControllerBase
{
    [HttpGet]


    public IActionResult Get()
    {
        return Ok("CORS is enabled for specific origins.");
    }
}

To disable CORS for a specific action, use the [DisableCors] attribute:
[HttpGet]

[DisableCors]

public IActionResult GetWithoutCors()
{
    return Ok("CORS is disabled for this action.");
}

Points to Remember

  1. Define CORS policies in AddCors.
  2. Use CORS middleware in Configure.
  3. Apply CORS globally, at the controller level, or at the action level.
  4. Use AllowCredentials carefully to avoid security risks.

By following these steps, you can enable and configure CORS in your ASP.NET Core Web API.

Need Help With .Net Development?

Work with our skilled .Net developers to accelerate your project and boost its performance.

Support On Demand!