使用 .NET Core WebApp 访问 AWS ElasticBeanstalk 自定义环境变量 [英] Access AWS ElasticBeanstalk Custom Environment Variables with .NET Core WebApp

查看:21
本文介绍了使用 .NET Core WebApp 访问 AWS ElasticBeanstalk 自定义环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在 Elastic Beanstalk 仪表板中的配置=>软件配置=>环境属性"部分下设置了自定义环境变量.在 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 Core 中,我们不再使用 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 FilesAmazonElasticBeanstalkconfigcontainerconfiguration", 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆