NetCore根据环境变量加载不同的配置文件

 

 

 

 

 public class Program
    {
        public static void Main(string[] args)
        {

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, builder) =>
            {
                string env = getENV(args);
                var c = builder.AddJsonFile(path: $"appsettings.{env}.json", optional: true, reloadOnChange: true).Build();

                var test = c.GetSection("NacosConfig").GetValue<string>("Namespace");
                builder.AddNacosV2Configuration(c.GetSection("NacosConfig"));
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });



        private static string getENV(string[] args)
        {
            string env = string.Empty;
            var ev = Environment.GetEnvironmentVariables();
            foreach (var item in ev.Keys)
            {
                if (item.ToString().ToLower() == "env")
                {
                    env = ev[item].ToString();
                }
            }
            Console.WriteLine($"env_v={env}");

            return env;





        }

    }

 

参考:

https://blog.csdn.net/qq_27843785/article/details/104421147

 

posted @ 2021-11-22 11:36  沐雪架构师  阅读(225)  评论(0编辑  收藏  举报