2
votes

According to microsoft blog the ASPNETCORE_ENVIRONMENT variable is loaded in order:

  1. appsettings.json file
  2. appsettings.{env.EnvironmentName}.json file
  3. The local User Secrets File
  4. Environment Variables
  5. Command Line Arguments (or equivalently launchSettings.json)

and "The last key loaded wins".

Questions:

But how can the file appsettings.{env.EnvironmentName}.json be loaded before the final Environment is known?

Can it happen that I set 'Staging' environment through command-line and appSettings.Development.json is loaded because during step 2 it is not yet known?

1

1 Answers

4
votes

There are two sets of configuration for an ASP.NET Core application:

  1. The configuration for the WebHost.
  2. The configuration for the application itself.

First the WebHost configuration is built (source):

_config = new ConfigurationBuilder()
    .AddEnvironmentVariables(prefix: "ASPNETCORE_")
    .Build();

As the source code shows, the configuration for the WebHost uses only environment variables and only those that are prefixed with ASPNETCORE_. One of those environment variables is, unsurprisingly, ASPNETCORE_ENVIRONMENT.

A little later down the line, an implementation of IHostingEnvironment is instantiated. This ends up using _config to retrieve a configuration setting named environment, which comes from the ASPNETCORE_ENVIRONMENT variable. If there is no such value, it defaults to Production.

Next up, the configuration for the application itself gets built. At step 2 in your question, the value of env.EnvironmentName is from the IHostingEnvironment I've already mentioned. If you were to set an environment value of e.g. Staging as a command-line argument, it would not change the value used in the WebHost configuration, as this applies only to the application configuration.

Andew Lock goes into more detail about how this all works and also demonstrates how to configure the WebHost to use additional configuration sources.