Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you use IConfiguration.GetSection() to read environment variables?

I am using Microsoft.Extensions.Configuration in .NET 6. I am trying to use IConfiguration.GetSection("MySection") to read all of the environment variables with the prefix MySection but it is not working.

For additional context: I want to do this so I can populate various application settings classes from the "Application settings" tab in an Azure Functions app.

Am I doing something wrong or is this use case not supported?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my program:

using Microsoft.Extensions.Configuration;
using System.Text.Json;

Environment.SetEnvironmentVariable("MySection__MyProperty", "fromEnvironmentVariable");
var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build();

Console.WriteLine(
    "Environment variable = " + 
    Environment.GetEnvironmentVariable("MySection__MyProperty")
);

Console.WriteLine(
    "configuration[\"MySection:MyProperty\"] = " + 
    configuration["MySection:MyProperty"]
);

Console.WriteLine(
    "configuration.GetSection(\"MySection\") = " +
    JsonSerializer.Serialize(configuration.GetSection("MySection"))
);

The program outputs:

Environment variable = fromEnvironmentVariable
configuration["MySection:MyProperty"] = fromEnvironmentVariable
configuration.GetSection("MySection") = {"Key":"MySection","Path":"MySection","Value":null}

I want the Value in the last line to contain fromEnvironmentVariable but it doesn’t.

>Solution :

Change this line;

JsonSerializer.Serialize(configuration.GetSection("MySection"))

To this;

JsonSerializer.Serialize(configuration.GetSection("MySection").GetChildren())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading