ASPNETCORE_ENVIRONMENT 开发 appsettings.Development.json 未加载

问题描述 投票:0回答:1

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

appsettings.jsonappsettings.Development.json

所以想法是在Development环境中加载文件appsettings.Development.json,在production环境中加载文件appsettings.json

launchSettings.json我改变了ASPNETCORE_ENVIRONMENT发展:

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

这按预期工作:

env.IsDevelopment() is true

应用程序设置是这样加载的:

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

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

我也试过:

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

但是在这种情况下,值总是从最后一个文件加载 appsettings.Development.json 即使:

env.IsDevelopment() is false
c# asp.net-core .net-core appsettings
1个回答
4
投票

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

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

对于

Development
环境会是
appsettings.Development.json
.
对于
Production
它将是
appsettings.Production.json
.

如果您没有这样的文件,则只会使用

appsettings.json
,因为您已经在该
optional: true
调用中设置了
AddJsonFile

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

您可能希望将

appsettings.json
设为必需的文件,以免在没有任何设置的情况下结束。

.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();
© www.soinside.com 2019 - 2024. All rights reserved.