Introduction
Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to restrict web applications from making requests to a domain different from the one that served the application. In .NET APIs, CORS needs to be explicitly enabled to allow requests from other origins. This article will guide you through the process of enabling CORS in a .NET API.
Configure CORS in the Program.cs
For .NET 6 and later versions, modify the Program.cs file to define and enable CORS.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
// Configure CORS policy
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigins", policy =>
{
policy.WithOrigins("https://example.com") // Specify allowed origins
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
// Enable CORS before using controllers
app.UseCors("AllowSpecificOrigins");
app.UseAuthorization();
app.MapControllers();
app.Run();
Allow All Origins (For Development Only)
If you need to allow all origins during development, modify the CORS policy as follows.
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
Then apply this policy using the app.UseCors("AllowAll").
Conclusion
Enabling CORS in a .NET API is essential when your front end and back end are hosted on different domains. Always restrict origins to specific trusted domains in production to maintain security. By following the steps outlined above, you can successfully configure and manage CORS in your .NET API.