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