CORS can be configured in three simple steps:
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();
});
});
}
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();
});
}
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.");
}
By following these steps, you can enable and configure CORS in your ASP.NET Core Web API.
Work with our skilled .Net developers to accelerate your project and boost its performance.
3rd Floor, Aval Complex, University Road, above Balaji Super Market, Panchayat Nagar Chowk, Indira Circle, Rajkot, Gujarat 360005.
Abbotsford, BC
15th B Street 103, al Otaiba Dubai DU 00000, United Arab Emirates
3rd Floor, Aval Complex, University Road, above Balaji Super Market, Panchayat Nagar Chowk, Indira Circle, Rajkot, Gujarat 360005.
Abbotsford, BC.
15th B Street 103, al Otaiba Dubai DU 00000, United Arab Emirates.
Copyright © 2026 Niotechone Software Solution Pvt. Ltd. All Rights Reserved.