I have defined below structure in my project.
appsettings.json
appsettings.development.json
appsettings.prod.json
appsettings.uat.json
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
});
webBuilder.UseStartup<Startup>();
});
}
I want server to read stage specific appsettings file. But all environments are reading appsettings.json always.
Are you copying your appsetting.json to the output directory?
If you want to use environment variables you should register them with .AddEnvironmentVariables()
like this:
I think .NET 5 and onward does this for you as long as DOTNET_ENVIRONMENT is set. https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.host.createdefaultbuilder?view=dotnet-plat-ext-7.0&viewFallbackFrom=net-6.0