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

Time:11-26

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?

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.

CodePudding user response:

Change this line;

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

To this;

JsonSerializer.Serialize(configuration.GetSection("MySection").GetChildren())
  • Related