appsettings.<env>.json is not getting used on server

709 views Asked by At

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.

1

There are 1 answers

1
Enrico On

Are you copying your appsetting.json to the output directory?

<ItemGroup>
      <None Update="appsettings.Development.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>         
      <None Update="appsettings.P.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>

If you want to use environment variables you should register them with .AddEnvironmentVariables()

like this:

public Startup(IWebHostEnvironment environment)
{
    _environment = environment ?? throw new ArgumentNullException(nameof(environment));

    Configuration = new ConfigurationBuilder()
        .SetBasePath(environment.ContentRootPath)
        .AddJsonFile("appsettings.json", false, true)
        .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}

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