Home > Blockchain >  ASPNETCORE_ENVIRONMENT Development appsettings.Development.json not loaded
ASPNETCORE_ENVIRONMENT Development appsettings.Development.json not loaded

Time:11-01

In my project i have the following files:

appsettings.json and appsettings.Development.json

so the idea is to load the file appsettings.Development.json in the Development environement and the appsettings.json for the production environement.

in the launchSettings.json i changed the ASPNETCORE_ENVIRONMENT to Development:

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }

this works as expected as the :

env.IsDevelopment() is true

the appsettings is loaded like this:

var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .Build();

but still all the values are loaded from the appsettings.json and not the appsettings.Development.json.

i also tried:

var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile("appsettings.Development.json", true, true)
                .Build(); 

but the values are always loaded from the last file in this case appsettings.Development.json even if the :

env.IsDevelopment() is false

CodePudding user response:

You need to compose the name of that environment specific settings file, instead of setting a fixed one.

$"appsettings.{env.EnvironmentName}.json"

For the Development environment it will be appsettings.Development.json.
For Production it will be appsettings.Production.json.

If you don't have such a file, only appsettings.json will be used, since you have set optional: true in that AddJsonFile call.

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, true)

You might want to make appsettings.json a required file in order to not end up without any settings.

.AddJsonFile("appsettings.json", optional: false, true)

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, true)
    .Build();
  • Related