I have an appsettings.json
file with a variable which is a list of strings: [“foo”, “bar”].
I’m trying to overwrite this variable with an environment variable. When I do, I still receive the value from appsettings when I retrieve the variable as a list. If I retrieve it as a string, I receive the environment variable value.
My current code is as follows:
appsettings.json
file:
{
"MyVariable": ["test"],
}
Program.cs
file:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
If I run the following code without injecting any environment variables, it works.
var result = config.GetSection("MyVariable").Get<List<string>>(); // returns a list with one element "test"
If I add the following environment variable and run again, I still get the same result: A list with one element “test”.
MyVariable=["foo", "bar"]
The odd thing is: If I run config.GetSection("MyVariable").Get<string>()
it returns this string: MyVariable=["foo", "bar"]
.
How do I define MyVariable
as a list, so I can still retrieve it with: config.GetSection("MyVariable").Get<List<string>>()
2
You need to use an environment variable per item, and the name should contain an index, like this:
MyVariable__0="foo"
MyVariable__1="bar"
The double underscore is interpreted as a section separator.