使用.NET Core WebApp访问AWS ElasticBeanstalk自定义环境变量 [英] Access AWS ElasticBeanstalk Custom Environment Variables with .NET Core WebApp
问题描述
我们已经在Elastic Beanstalk仪表板的configuration => software configuration => Environment Properties部分下设置了自定义环境变量。在C#MVC 5项目中,我们可以通过使用ConfigurationManager.AppSettings查找它们来访问这些变量-效果很好。
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.
在.NET核心中,我们不这样做不再使用web.config。我们一直在尝试寻找一种访问环境变量的方法,但我们发现的只是一个名为AWSSDK.Extensions.NETCore.Setup的nuget程序包。但是,此程序包似乎无法使我们访问自定义变量。
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.
任何帮助将不胜感激。
推荐答案
根据我的研究和测试,这是针对ASP.NET Core 1.1应用程序的AWS Elastic Beanstalk的不足。今天就刚遇到这个问题,解决此问题的唯一方法是使用ASP.NET ConfigurationBuilder加载AWS编写的配置(如果有的话)。
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最终应解决此问题,直到您可以使用我使用的方法:
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;
}
这篇关于使用.NET Core WebApp访问AWS ElasticBeanstalk自定义环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!