Search code examples
c#.netlinuxconsole-application.net-6.0

.NET 6 console app on Linux - environment name is empty


I need to load settings from appsettings.{environment}.json in my console app on Linux, and I use the following code:

private static async Task Main(string[] args)
{
    using IHost host = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, configuration) =>
        {
            // IHostEnvironment env = hostingContext.HostingEnvironment;
            //  ==>  env.EnvironmentName is EMPTY

            string? environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
            if (string.IsNullOrWhiteSpace(environmentName)) environmentName = string.Empty;

            configuration.AddJsonFile("./appsettings.json");
            //  ==> here it's EMPTY too !
            configuration.AddJsonFile($"./appsettings.{environmentName}.json".ToLowerInvariant());
        })
   ...
}

I set the DOTNET_ENVIRONMENT to some-environment-name, which I can check with echo $DOTNET_ENVIRONMENT. I set this env variable in ~/.bashrc (export DOTNET_ENVIRONMENT=somename). And currently I run the app from bash, connecting to linux machine over SSH, so it's just ./MyApp command.

When I run the app, I get the empty value as the environment name. Why might this happen?

Additional info

My app is a self-contained app.


Solution

  • ok, my bad! I run my app not just with ./MyApp command. I used:

    sudo ./MyApp
    

    In the case of sudo the environment is completely new, thus there are no variables defined for the user I'm currently using in shell. In order to pass those variables, I need to specify them in the command explicitely:

    sudo DOTNET_ENVIRONMENT=myenv ./MyApp