WebHost启动后是否可以添加到IConfiguration?

时间:2019-05-31 11:13:53

标签: amazon-web-services .net-core amazon-systems-manager

我正在使用AWS Systems Manager参数存储来保存数据库连接字符串,这些字符串用于在.NET Core应用程序中动态构建DbContext

我正在使用.NET Core AWS配置提供程序(来自https://aws.amazon.com/blogs/developer/net-core-configuration-provider-for-aws-systems-manager/),该提供程序在运行时将参数注入IConfiguration。

此刻,我必须将我的AWS访问密钥/秘密保存在代码中,以便ConfigurationBuilder可以对其进行访问,但希望将其移出代码库并将其存储在appsettings或类似文件中。

这是我创建启动时调用的Webhost构建器的方法

    def forgot_password
      resource = Patient.find(params[:id])
      send_mail = PatientMailer.reset_password_instructions(
        resource: resource,
        token: resource.set_reset_password_token
      ).deliver_later
      redirect_to edit_patient_registration_path(patient)
      if send_mail.deliver_later.success?
        flash[:notice] = I18n.t("devise.registrations.edit.forgot_password_email_sent")
      else
        flash[:alert] = "FAIL"
      end
    end

我需要能够从某个地方注入BasicAWSCredentials参数。

1 个答案:

答案 0 :(得分:1)

您需要访问已构建的配置才能检索您要查找的信息。

考虑构建一个以检索所需的凭据

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    var access_key = configuration.GetValue<string>("access_key:path_here");
    var secret_key = configuration.GetValue<string>("secret_key:path_here");

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);

    AWSOptions options = new AWSOptions() {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config => {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

    return webHost;
}

我还建议您从文档中查看Configuring AWS Credentials,以使用SDK来找到一种可能的替代方式来存储和检索凭据。