I want to read appsettings.json then replace the keys based on each environment. After a lot of research I feel clueless, I read other posts about something similar but the solutions provided didn't help, the implementation in Program.cs should work in theory but the application keeps using just appsettings.json.
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment}.json", optional: true, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
public static string Environment
{
get
{
string environmentName;
#if DEBUG
environmentName = "Development";
#elif RELEASE
environmentName = "Test";
#endif
return environmentName;
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"myconn": "connection"
}
}
appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"myconn": "connectionDev"
}
}
{
"ConnectionStrings": {
"myconn": "connectionDev"
}
}
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:49416/",
"sslPort": 44368
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express Test": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Test"
}
},
"WICAPI": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
ASP.NET Core actually does that for you. There's no need to do anything. Leave
Program.cs
as default:The general configuration must be on
appsettings.json
and just write the configs you want to override fromappsettings.json
in yourappsettings.{env}.json
file, being{env}
the name of the environment, eg:appsettings.json
appsettings.Development.json