编程语言
首页 > 编程语言> > .net ASPNETCORE_ENVIRONMENT 根据环境切换不同的配置文件

.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 来切换环境

[参考]
ASP.NET CORE 根据环境变量支持多个 appsettings.json

标签:配置文件,config,ASPNETCORE,args,hostingContext,ENVIRONMENT,json,appsettings,true
来源: https://www.cnblogs.com/ives/p/16548240.html