
February 10, 2025 06:26 by
Peter
A crucial component of online applications is Cross-Origin Resource Sharing (CORS), which permits or prohibits the sharing of resources between several origins (domains). The client and server of a contemporary web application are frequently housed on separate domains. When the client sends HTTP requests to the server, this may result in CORS problems. We'll look at how to set up CORS to dynamically permit numerous origins from your appsettings in this post.in a.NET Core JSON file.
Configure CORS in the appsettings.JSON
We must first specify the permitted origins in the appsettings.json file in order to permit multiple origins. The list of URLs (origins) from which cross-origin requests are permitted will be stored here.
{
"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.
European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.
