ASPNETCORE_ENVIRONMENT 开发 appsettings.Development.json 未加载

KA-*_*sso 5 c# appsettings .net-core asp.net-core

在我的项目中,我有以下文件:

appsettings.jsonappsettings.Development.json

所以我们的想法是在开发环境中加载文件appsettings.Development.json ,在生产环境中加载appsettings.json

launchSettings.json中,我将ASPNETCORE_ENVIRONMENT更改为 Development:

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

这按预期工作:

env.IsDevelopment() is true
Run Code Online (Sandbox Code Playgroud)

appsettings 的加载方式如下:

var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .Build();
Run Code Online (Sandbox Code Playgroud)

但所有值仍然是从 appsettings.json 而不是 appsettings.Development.json 加载的。

我也尝试过:

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

但在本例中,值始终从最后一个文件加载 appsettings.Development.json,即使:

env.IsDevelopment() is false
Run Code Online (Sandbox Code Playgroud)

pfx*_*pfx 7

您需要编写特定于环境的设置文件的名称,而不是设置固定的文件。

$"appsettings.{env.EnvironmentName}.json"
Run Code Online (Sandbox Code Playgroud)

对于Development环境来说将会如此 appsettings.Development.json
因为Production它将是appsettings.Production.json

如果您没有这样的文件,则只会appsettings.json使用,因为您已optional: true在该AddJsonFile调用中进行了设置。

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, true)
Run Code Online (Sandbox Code Playgroud)

您可能想要创建appsettings.json一个必需的文件,以免最终没有任何设置。

.AddJsonFile("appsettings.json", optional: false, true)
Run Code Online (Sandbox Code Playgroud)
var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, true)
    .Build();
Run Code Online (Sandbox Code Playgroud)