在我的项目中,我有以下文件:
appsettings.json和appsettings.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)