'.NET Core console app and aspnetcore_environment variable

I have a .net core CONSOLE app. In the code I am reading in the appropriate environment specific appsettings.dev.json, appsettings.uat.json etc.

  var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("appsettings.json", false)
                .AddJsonFile($"appsettings.{environmentName}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();

When this is run directly in Visual Studio the ASPNETCORE_ENVIRONMENT variable is set from the launchSettings.json file or from amending the project properties, debug tab and the correct appsettings.environment.json file is read.

When i want to publish the project via Visual Studio i.e. right click project and publish (i.e. I do not want to do this via the command line) I select the appropriate .pubxml file held within PublishProfile folder. In this .pubxml file I have set the environmentName.

  <EnvironmentName>dev</EnvironmentName>

However, when running the exe that is produced by the publish process - the environmentName variable specified above is always blank and consequently it doesn't pick up the correct environmentName setting and hence the appropriate appsettings.environment.json file is not read in.



Solution 1:[1]

When you want to run published .exe file try this way in command line(powershell):

$env:ASPNETCORE_ENVIRONMENT="dev";yourfile.exe

Solution 2:[2]

I discovered that if I change the actual Machine environment variable (ASPNETCORE_ENVIRONMENT), the deployed application adjust accordingly.

Remember! (This application is already published - Its behavior changes as I update the variable on the box and restart the application)

Click to see image below

enter image description here

ASPNETCORE_ENVIRONMENT : When it's set to Production my application uses the appsettings.production.json file

ASPNETCORE_ENVIRONMENT : When it's set to Development my application uses the appsettings.Development.json file

Click to see image below enter image description here

I also discovered that I actually had to restart my Visual Studio 2019 in order for the newly added environment variable to take affect. Basically, I believe the environment variables are being cached some how behind the scenes. Therefore, if you do add another variable you may have to restart Visual Studio in order for them to take affect. ... Hummmm

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saeed Esmaeelinejad
Solution 2