Using Different CORS Policies for Endpoints in ASP.NET
Sometimes you might need different CORS policies for specific endpoints in your application. Imagine most endpoints of your API communicate exclusively with a frontend hosted at sample.com. You configure a general CORS policy for this domain (e.g., AllowSampleCom) allowing requests only from the origin sample.com.
However, one or more endpoints might need to accept requests from another domain, for example, admin-sample.com. In such cases, you can conveniently create a separate policy, such as AllowAdminSampleCom, specifically tailored for this domain.
public class Program
{
public void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSampleCom", policy =>
{
policy.WithOrigins("https://sample.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
options.AddPolicy("AllowAdminSampleCom", policy =>
{
policy.WithOrigins("https://admin-sample.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
app.UseCors("AllowSampleCom");
app.MapControllers();
app.Run();
}
}
You can then selectively apply this policy to your endpoints:
For controllers, use the attribute:
[EnableCors("AllowAdminSampleCom")]
For Minimal APIs, use the method:
app.MapGet("/endpoint", handler).RequireCors("AllowAdminSampleCom");
Here’s a simple example for a controller endpoint:
[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
[HttpPost("AddUser")]
[EnableCors("AllowAdminSampleCom")]
public IActionResult AddUser()
{
// Logic to add a user
return Ok();
}
}
If you need to completely disable CORS for specific endpoints, use the following attribute:
[DisableCors]
This approach provides flexibility, allowing you to tailor CORS behavior based on the specific needs of each endpoint while maintaining a secure and organized backend.