Comprehensive Guide to Enabling CORS in ASP.NET Core

Nov 19, 2025 · Programming · 14 views · 7.8

Keywords: ASP.NET Core | CORS | Cross-Origin Resource Sharing | Web API | Middleware Configuration

Abstract: This article provides a detailed guide on enabling Cross-Origin Resource Sharing (CORS) in ASP.NET Core Web API. Starting from the basic concepts of CORS, it thoroughly explains the meaning and function of the policyName parameter, and demonstrates specific configuration methods in ASP.NET Core 6 and earlier versions through complete code examples. The content covers named policy configuration, middleware usage, attribute application, and detailed explanations of various CORS policy options, offering developers a complete and reliable CORS implementation solution.

CORS Fundamentals

Cross-Origin Resource Sharing (CORS) is a W3C standard that allows servers to relax the same-origin policy restrictions. The same-origin policy is a security mechanism implemented by browsers that prevents web pages from requesting resources from different domains. When a Web API needs to be accessed by client applications from different domains, CORS must be enabled.

CORS is not a security feature but rather a mechanism that relaxes security restrictions. An API does not become more secure by allowing CORS, so careful configuration of allowed domains is essential in practical applications.

Understanding the policyName Parameter

The policyName parameter in the EnableCors attribute is a string that identifies a specific CORS policy configured during application startup. This name is arbitrary but must remain consistent throughout the application.

The policy name serves to:

ASP.NET Core 6 Configuration

In ASP.NET Core 6, CORS configuration is primarily done in the Program.cs file:

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy =>
                      {
                          policy.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

builder.Services.AddControllers();

var app = builder.Build();

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

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();
app.MapControllers();
app.Run();

Key steps in the above code:

  1. Define policy name constant
  2. Register CORS service and configure policy in the service container
  3. Enable CORS in the middleware pipeline
  4. Ensure UseCors is called after UseRouting and before UseAuthorization

Configuration for Earlier Versions

For ASP.NET Core 3.1 and 5.0, configuration is done in the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.WithOrigins("http://example.com")
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

    services.AddControllers();
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");
    app.UseMvc();
}

CORS Policy Configuration Options

CORS policies provide rich configuration options to meet different security requirements:

Allowed Origins

policy.WithOrigins("http://example.com", "http://www.contoso.com");

Allowed Methods

policy.WithMethods("GET", "POST", "PUT", "DELETE");
policy.AllowAnyMethod(); // Allow all HTTP methods

Allowed Headers

policy.WithHeaders(HeaderNames.ContentType, "x-custom-header");
policy.AllowAnyHeader(); // Allow all request headers

Credentials Handling

policy.AllowCredentials(); // Allow cross-origin requests to include credentials

Attribute-Level CORS Control

In addition to global configuration, CORS can be applied at the controller or action method level:

[EnableCors("MyPolicy")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok("Hello World");

    [DisableCors]
    [HttpGet("private")]
    public IActionResult GetPrivate() => Ok("Private data");
}

Preflight Request Handling

For certain CORS requests, browsers first send OPTIONS preflight requests. ASP.NET Core automatically handles these requests, but manual handling is also possible:

[HttpOptions("{id}")]
public IActionResult PreflightRoute(int id)
{
    return NoContent();
}

Security Considerations

When configuring CORS, consider the following security aspects:

Testing and Debugging

You can test CORS configurations using browser developer tools or command-line tools:

curl -X OPTIONS https://yourapi.com/api/values -H "Origin: http://example.com" -v

Verify configuration correctness by checking CORS-related headers like Access-Control-Allow-Origin in the response headers.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.