Cross-Origin Resource Sharing (CORS) is an important feature in web applications that allows or restricts resources to be shared across different origins (domains). In a modern web application, it’s common to have the client and server hosted on different domains. This can lead to CORS issues when making HTTP requests from the client to the server.
In this article, we will explore how to configure CORS to allow multiple origins dynamically from your appsettings.json file in a .NET Core
Add CORS Configuration in appsettings.json
To allow multiple origins, first, we need to define the allowed origins in the appsettings.json file. This will store the list of URLs (origins) from which cross-origin requests are allowed.
{
"Cors": {
"AllowedOrigins": [
"https://example1.com",
"https://example2.com",
"https://example3.com"
]
}
}
Read the Configuration in Program.cs
var builder = WebApplication.CreateBuilder(args);
// Get allowed origins from appsettings.json
var allowedOrigins = builder.Configuration
.GetSection("Cors:AllowedOrigins")
.Get<string[]>();
// Add CORS policy
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigins",
builder => builder.WithOrigins(allowedOrigins) // Apply multiple origins dynamically
.AllowAnyMethod()
.AllowAnyHeader());
});
// Add services to the container (e.g., AddControllers)
builder.Services.AddControllers();
var app = builder.Build();
// Use CORS policy
app.UseCors("AllowSpecificOrigins");
// Configure the HTTP request pipeline
app.MapControllers();
app.Run();
Apply CORS Policy in the Middleware
// Apply the CORS policy globally
app.UseCors("AllowSpecificOrigins");
// Other middleware (e.g., UseRouting, UseEndpoints)
Conclusion
Using appsettings.json to manage CORS settings in your .NET Core 9 application allows for greater flexibility and better maintainability. You can easily add or remove origins without changing your application's code. This is particularly useful when deploying your application to different environments (development, staging, production) with different origin policies.
By following these steps, you can dynamically configure and manage multiple allowed origins for your application.