调整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 来切换环境
[参考]
ASP.NET CORE 根据环境变量支持多个 appsettings.json