o..o
o..o

Reputation: 1921

How to read environment variables in .NET 6?

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

Upvotes: 9

Views: 44838

Answers (2)

Phrynohyas
Phrynohyas

Reputation: 156

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:

public class MyConfig
{
  public string ValueA { get; set; }
  public int ValueB { get; set; }
}

Let's also assume there are environment variables set to MySection__ValueA and MySection__ValueB.

If you register a config class as:

services.Configure<MyConfig>("MySection");

Then you will be able to access the configuration values in the code as:

public class SomeService
{
  public SomeService(IOptions<MyConfig> config)
  {
    // Here config.Value.ValueA is equal to MySection__ValueA
    // and config.Value.ValueB is equal to MySection__ValueB (automatically converted to int)
  }

Upvotes: 14

Pablo Urquiza
Pablo Urquiza

Reputation: 735

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

Upvotes: 6

Related Questions