What is CORS?

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to restrict how resources on a web page can be requested from another domain. By enabling CORS, you allow your ASP.NET Core Web API to accept requests from specific origins or domains.

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:

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:

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:

[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.

Support On Demand!

.Net

Related Q&A