Access AWS ElasticBeanstalk Custom Environment Variables with .NET Core WebApp

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

We have set custom environment variables in the Elastic Beanstalk dashboard, under configuration=>software configuration=>"Environment Properties" section. In a C# MVC 5 project, we can just access these variables by looking for them with ConfigurationManager.AppSettings - that works great.

In .NET core, however, we don't use web.config anymore. We've been attempting to track down a way to access the environment variables, but all we've found is a nuget package called AWSSDK.Extensions.NETCore.Setup. However, this package does not seem to get us the access to the custom variables.

Any help would be greatly appreciated.

回答1:

Based on my research and testing, this is a deficiency in AWS Elastic Beanstalk for ASP.NET Core 1.1 applications. Just ran into this issue today and the only way to solve it is to load the config that AWS writes (if it's there) using the ASP.NET ConfigurationBuilder and parse it.

AWS should eventually fix this, until then you can use the method I'm using:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!