.net ASPNETCORE_ENVIRONMENT 根据环境切换不同的配置文件
调整program.cs文件中的CreateHostBuilder方法
//从hostingContext.HostingEnvironment.EnvironmentName中获取对应的环境名称
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext,config) =>
{
config.Sources.Clear();
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
Console.WriteLine($"appsettings.{env.EnvironmentName}.json");
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.UseContentRoot(AppDomain.CurrentDomain.BaseDirectory)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseUrls($"http://{ip}:{port}")
.UseStartup<Startup>()
;
})
.UseWindowsService();
}
hostingContext.HostingEnvironment对象下包含四个可以判断当前环境的方法
IsDevelopment()
IsStaging()
IsProduction()
IsEnvironment()
可以通过配置环境变量(windows中为系统变量) ASPNETCORE_ENVIRONMENT 来切换环境
另外也可以通过修改launchSettings.json文件中的environmentVariables来读取不同的配置
通过AddJsonFile添加的顺序需要格外注意,在底层通过ConfigurationRoot的索引获取值的时候会倒序取出第一个配置文件然后将值返回。
所以需要先添加默认的appsetting.json然后再添加具体的环境配置。
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
2021-08-03 jenkins远程发布
2016-08-03 摸板模式与钩子