无法使用环境变量覆盖 appsettings.json 设置 [英] can't override appsettings.json settings with environment variables

查看:22
本文介绍了无法使用环境变量覆盖 appsettings.json 设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用环境变量覆盖我的 appsettings.json 文件的设置.

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"
    }
  },
}

主要内容:

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();
}

环境变量:

更新 1:

在这里我可以看到,我的所有提供者都已注册:

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

真正奇怪的是:在环境变量列表中,大约有 80 个条目.我的两个新变量不见了,但其中有 2 个环境变量,这是我几个小时前创建并立即删除的.他们到底是从哪里来的?!

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?!

更新 2:

我重新启动了我的计算机,现在我在列表中看到了我的环境变量,但它没有覆盖 appsettings.json 中的值?

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

推荐答案

从您的环境变量中移除 ASPNETCORE_ 前缀或将其作为参数添加到 AddEnvironmentVariables,没有默认前缀.

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

尝试枚举配置以查看键是否按预期排列.

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);
    }
}

这篇关于无法使用环境变量覆盖 appsettings.json 设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆