in my .NET Core 3.1 WebApi project I’m reading environment variable as the very first thing and loading appsettings.json according to it:
public static IHostBuilder CreateHostBuilder(string[] args)
{
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
...
}
But I didn’t find out how to read it in .NET 6:
var builder = WebApplication.CreateBuilder(args);
build.Environment has no way to read it.
Anyone knows?
Thanks
2
Answers
The official documentation says that the method in the System namespace should work:
https://learn.microsoft.com/en-us/dotnet/api/system.environment.getenvironmentvariable?view=net-6.0
I want to extend the accepted answer a bit, since it only references a link.
It is also possible to read environment variables into strongly typed configuration classes.
I.e., take a look at this class:
Let’s also assume there are environment variables set to
MySection__ValueA
andMySection__ValueB
.If you register a config class as:
Then you will be able to access the configuration values in the code as: