skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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)
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search