Search code examples
c#asp.net-core.net-core

can't override appsettings.json settings with environment variables


I can't override the settings of my appsettings.json file with environment variables.

appsettings.json:

{
  "AppSettings": {
    "LocalUpdatesDir": "<some path>",
    "BinaryDeltaCount": 5,
    "BinaryDeltaFilenameTemplate": "<template>",
    "Azure": {
      "User": "user here",
      "Password": "password here"
    }
  },
}

Main:

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

Environment variables:

enter image description here

Update 1:

Here I can see, that all my providers are registered:

enter image description here

What's really strange: In the environments variable list, there are about 80 entries in it. My two new ones are missing, BUT there are 2 environment variables in it, which I created a few hours ago and deleted right away. WHERE THE HECK ARE THEY COMING FROM?!

Update 2:

I restarted my computer and now I see my Environment variable in the list, but it doesn't override the value in appsettings.json?


Solution

  • Remove the ASPNETCORE_ prefix from your env variables or add it as a parameter to AddEnvironmentVariables, there's no prefix by default.

    Edit: Try enumerating the config to see if the keys are lining up as you'd expect.

    private static void ShowConfig(IConfiguration config)
    {
        foreach (var pair in config.GetChildren())
        {
            Console.WriteLine($"{pair.Path} - {pair.Value}");
            ShowConfig(pair);
        }
    }