AWS Elastic Beanstalk environment variables in ASP.NET Core 1.0

后端 未结 9 2026
误落风尘
误落风尘 2020-12-01 02:59

How do I get environment variables from elastic beanstalk into an asp.net core mvc application? I have added a .ebextensions folder with app.config file in it with the follo

9条回答
  •  醉酒成梦
    2020-12-01 03:22

    Above solution doesnt helped me to load config file based on enviroment settings. So here is my solution AWS ElasticBeansTalk "hack"

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{GetEnvVariableAWSBeansTalkHack(env)}.json", optional: true)
                .AddEnvironmentVariables();
    
            Configuration = builder.Build();
        }
    
        private static string GetEnvVariableAWSBeansTalkHack(IHostingEnvironment env)
        {
            var config = new ConfigurationBuilder()
               .AddJsonFile(@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration", optional: true, reloadOnChange: true).Build();
    
            Dictionary dict = new Dictionary();
            foreach (IConfigurationSection pair in config.GetSection("iis:env").GetChildren())
            {
                string[] keypair = pair.Value.Split(new[] { '=' }, 2);
                dict.Add(keypair[0], keypair[1]);
            }
    
            return dict.ContainsKey("ASPNETCORE_ENVIRONMENT") 
                    ? dict["ASPNETCORE_ENVIRONMENT"] 
                    : env.EnvironmentName;
        }
    

提交回复
热议问题