我们有.NET Core 2.2 Web API项目,我们使用以下代码加载基于appsettings.json
或DEBUG
构建标志的相应RELEASE
文件。
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
#if DEBUG
.AddJsonFile("appsettings.Development.json")
#endif
#if RELEASE
.AddJsonFile("appsettings.Production.json")
#endif
.AddJsonFile("appsettings.json")
.Build()
)
.UseStartup<Startup>()
.Build();
我们创建了一个外部项目,它在Topshelf Windows服务项目中调用相同的方法。
奇怪的是,无论我们是在调试还是发布项目,appsettings.Production.json
文件总是被加载。
执行以下操作,然后在托管系统OS中设置环境变量:
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
public static IWebHost BuildWebHost(string[] args) =>
WebHost
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", true, true)
.AddJsonFile($"appsettings.{environmentName}.json", true, true)
.Build()
)
.UseStartup<Startup>()
.Build();
编辑:删除CreateDefaultBuilder()
备注
以下默认值应用于返回的WebHostBuilder:
- 使用Kestrel作为Web服务器并使用应用程序的配置提供程序对其进行配置,
- 将ContentRootPath设置为GetCurrentDirectory()的结果,
- 从qazxsw poi和qazxsw poi加载配置,
- 使用条目程序集环境名称为“开发”时从用户秘密加载IConfiguration,
- 从环境变量加载配置,
- 从提供的命令行参数加载IConfiguration,
- 配置ILoggerFactory以记录控制台和调试输出,
- 并启用IIS集成。
该列表中的数字3始终将查看appsettings.json
环境变量的值(如果未指定,则默认为“Production”),并尝试加载具有该名称的appsettings文件。
而不是更改代码或使用预处理程序指令,只需更改该环境变量的值(例如,“开发”)。
这就是你的appsettings.[EnvironmentName].json
文件的工作原理:
ASPNETCORE_ENVIRONMENT
不要与launchSettings.json
战斗 - 您发布的代码执行了该方法已经为您执行的许多步骤(加载文件,设置基本路径等)。
这是ASP.Net Core项目给你的默认Program.cs,它对你很有用:
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
...
另外,只需注意,您将在主appsettings.json文件之前加载特定于环境的文件。通常你会想要以其他顺序这样做。