In prior versions of ASP.NET Core we could dynamically add appsetting.json files with the environment suffix like appsettings.Production.json
for production environment.
Since the structure is a bit different, it seems that the configuration now got loaded in class Program
. But we dont have the `` injected here,so I tried it myself using environment variable:
public class Program {
public static void Main(string[] args) {
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
string envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
string envConfigFile = $"appsettings.{envName}.json";
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(envConfigFile, optional: true);
var finalConfig = config.Build();
return WebHost.CreateDefaultBuilder(args)
.UseUrls("http://0.0.0.0:5000")
.UseConfiguration(finalConfig)
.UseStartup<Startup>();
}
}
The code got executed but it doesn't override my appsettings.json
config. Let's say I have the following appsettings.json
:
{
"MyConnectionString": "Server=xxx,Database=xxx, ..."
}
This ConnectionString is working. Now I createappsettings.Development.json
{
"MyConnectionString": ""
}
and set ASPNETCORE_ENVIRONMENT=Development
. This should definitely throw an exception. But the app start correctly with the ConnectionString from appsettings.json
.
According to ASP.NET Core 2 configuration changes, the WebHost.CreateDefaultBuilder
method should itself use the new ConfigureAppConfiguration
approach and load environment specific config by default. Also the official docs say that appsettings.{Environment}.json
are loaded automatically. But this doesn't work and also loading it manually like this doesn't solve the problem:
return WebHost.CreateDefaultBuilder(args)
.UseUrls("http://0.0.0.0:5000")
.ConfigureAppConfiguration((builderContext, config) => {
IHostingEnvironment env = builderContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>();
How can I override the config using "appsettings.{envName}.json"
pattern? I liked that cause it was handy to override env specific things in ASP.NET Core.