c# - .NET Core AWS RDS 连接

标签 c# amazon-web-services .net-core amazon-rds asp.net-core-webapi

我正在 Amazon AWS Elastic Beanstalk 上创建 .NET Core Web API。 我正在尝试添加数据库,但他们的添加数据库指南不适用于 .Net Core http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_NET.rds.html

它说使用“​​ConfigurationManager.AppSettings;”获取相关信息,但这在.NET Core中是不可能的。

有人可以提供一些有关如何获取数据库信息的信息吗? ( “RDS_DB_NAME” “RDS_用户名” “RDS_密码” “RDS_HOSTNAME” )

更新 我尝试阅读 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration 但我还没有解决问题。我似乎仍然无法从 AWS 获取值。

它只返回我在自己的 appsettings.json 中设置的内容 这是我的代码: 我的选项.cs

public class MyOptions
{
    public MyOptions()
    {
        // Set default value.
    }
    public string RDS_HOSTNAME { get; set; }
    public string RDS_PORT { get; set; }
    public string RDS_DB_NAME { get; set; }
    public string RDS_USERNAME { get; set; }
    public string RDS_PASSWORD { get; set; }
}

StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
    // Register the IConfiguration instance which MyOptions binds against.
    services.Configure<MyOptions>(Configuration);
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();
}

HomeController.cs

namespace WebApplication2.Controllers
{
    [Route("")]
    public class HomeController : Controller
    {
        private readonly MyOptions _options;

        public HomeController(IOptions<MyOptions> optionsAccessor)
        {
            _options = optionsAccessor.Value;
        }

        [HttpGet]
        public IActionResult Index()
        {
            var RDS_DB_NAME = _options.RDS_DB_NAME;
            var RDS_HOSTNAME = _options.RDS_HOSTNAME;
            var RDS_PASSWORD = _options.RDS_PASSWORD;
            var RDS_PORT = _options.RDS_PORT;
            var RDS_USERNAME = _options.RDS_USERNAME;
            return Content($"RDS_DB_NAME = {RDS_DB_NAME}, RDS_HOSTNAME = {RDS_HOSTNAME}, RDS_PASSWORD = { RDS_PASSWORD}, RDS_PORT = {RDS_PORT}, RDS_USERNAME = { RDS_USERNAME}");
        }
    }
}

最佳答案

我遇到了这个确切的问题,它比我预期的要复杂得多。

第 1 步 - 我修改了 this answer来自另一个堆栈溢出问题。我在 Startup.cs 中的代码如下所示:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
        .AddJsonFile(@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    // This adds EB environment variables.
    builder.AddInMemoryCollection(GetAwsDbConfig(builder.Build()));

    Configuration = builder.Build();
}

private Dictionary<string, string> GetAwsDbConfig(IConfiguration configuration)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();

        foreach (IConfigurationSection pair in configuration.GetSection("iis:env").GetChildren())
        {
            string[] keypair = pair.Value.Split(new[] { '=' }, 2);
            dict.Add(keypair[0], keypair[1]);
        }

        return dict;
    }

private string GetRdsConnectionString()
{
    string hostname = Configuration.GetValue<string>("RDS_HOSTNAME");
    string port = Configuration.GetValue<string>("RDS_PORT");
    string dbname = Configuration.GetValue<string>("RDS_DB_NAME");
    string username = Configuration.GetValue<string>("RDS_USERNAME");
    string password = Configuration.GetValue<string>("RDS_PASSWORD");

    return $"Data Source={hostname},{port};Initial Catalog={dbname};User ID={username};Password={password};";
}

第 2 步 - 您需要转到 AWS 控制台中的 RDS 服务。选择要连接的实例 -> 实例操作 -> 查看详细信息。您将能够找到 RDS_HOSTNAME(端点)和 RDS_PORT(端口)。

RDS_DB_NAME 是您的代码要使用的数据库名称。

RDS_USERNAME 和 RDS_PASSWORD 是您在 Elastic Beanstalk 中创建数据库时使用的主用户名和密码。如果您转到 Elastic Beanstalk -> 配置 -> 数据层 ->(单击齿轮),您会看到您的主用户名,并且可以选择更改您的密码(如果您忘记了密码)。

第 3 步 - 现在您已拥有所有数据,您必须在 Elastic Beanstalk 中输入这些选项作为环境属性。转至 Elastic Beanstalk -> 软件配置 ->(单击齿轮)。此页面底部是环境属性。您需要在此处输入第一步中代码中的名称以及第二步中 RDS 中的值。

有关 AWS 文档的更多信息,请查看 herehere .

关于c# - .NET Core AWS RDS 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44532117/

相关文章:

amazon-web-services - 正在寻找监控 ECS 部署失败通知的好方法?

ruby-on-rails - MultiJson AdapterError Rails 4 Ruby 2 乘客

c# - 在 dotnet mvc 应用程序中连接到 Oracle 数据库

c# - 如何仅在 SQLite 中更新 1 行

C# 字互操作表形状位置

python - 如何将资源的引用传递给 CFN 模板中的 python 字典?

.net-core - 仅编译时 Nuget 依赖项 (FxCop)

c# - 将大文件发布到 REST Endpoint c# .net core

c# - 将 FlowDocument 作为 XPS 文档保存到磁盘

C# 快捷方式或速记 getter setter