Override App.config value with an environment variable

流过昼夜 提交于 2020-12-08 06:26:26

问题


I have a C# console program that prints an App.config value. Can I override this value from an environment variable?

In my real use-case, the value specifies a port to bind, and I need to run multiple instances of the program in my Jenkins server, so each one should have a different value even though they use the same config file.

Example App.config:

  <appSettings>
    <add key="TestKey" value="Foo"/>
  </appSettings>

Example Code:

  Console.WriteLine($"Key: {ConfigurationManager.AppSettings["TestKey"]}");

I tried just setting the Key name but that obviously doesn't work:

c:\Workspace\ConsoleApp2\ConsoleApp2\bin\Debug>set TestKey=Bar
c:\Workspace\ConsoleApp2\ConsoleApp2\bin\Debug>ConsoleApp2.exe
Key: Foo

回答1:


The ConfigurationManager class doesn't do that for you, it will only read from your app config. To fix this, you can use a function to get the variable and use that instead of calling ConfigurationManager.AppSettings directly. This is good practice to do anyway as it means you can easily move your config into a JSON file or a database and you won';t need to update every usage of the old method.

For example:

public string GetSetting(string key)
{
    var value = Environment.GetEnvironmentVariable(key);

    if(string.IsNullOrEmpty(value))
    {
        value = ConfigurationManager.AppSettings[key];
    }

    return value;
}



回答2:


in netcore (aspnetcore) you can override settings in environments https://github.com/dotnet/AspNetCore.Docs/issues/11361#issuecomment-471680877

need use prefix ASPNETCORE_youvariable (ASPNETCORE - default value).



来源:https://stackoverflow.com/questions/52404567/override-app-config-value-with-an-environment-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!