使用 ConfigurationBuilder 检索 Web App 连接字符串

Retrieving Web App connection strings using ConfigurationBuilder

我们将一些敏感键和连接字符串存储在 Web App 应用程序设置下的 连接字符串 部分:

我们使用 ConfigurationBuilder:

检索配置设置
Configuration = new ConfigurationBuilder()
    .SetBasePath(environment.ContentRootPath)
    .AddEnvironmentVariables()
    .Build();

我原以为 AddEnvironmentVariables() 会选择这些连接字符串,但事实并非如此。请注意,如果您在 Web 应用程序中将这些值设置为 "App settings",这确实有效。

经过仔细检查(使用 Kudu 控制台),我发现为这些连接字符串设置的环境变量在键名前添加了 CUSTOMCONNSTR_

CUSTOMCONNSTR_MongoDb:ConnectionString=...
CUSTOMCONNSTR_Logging:ConnectionString=...
CUSTOMCONNSTR_ApplicationInsights:ChronosInstrumentationKey=...

我现在应该如何使用 ConfigurationBuilder 读取这些连接字符串?

编辑:

我发现一个方便的 AddEnvironmentVariables 重载存在一个 prefix 参数,描述为:

//   prefix:
//     The prefix that environment variable names must start with. The prefix will be
//     removed from the environment variable names.

但是将 .AddEnvironmentVariables("CUSTOMCONNSTR_") 添加到配置生成器也不起作用!

它应该可以正常工作,并且在我的示例应用程序中对我有用:https://github.com/davidebbo-test/AspNetCoreDemo。具体来说:

  • MyDatabase 连接字符串定义为 here.
  • 使用here.
  • 如果您在 Azure 门户中定义 MyDatabase conn 字符串,您将在运行时看到新值(转到“关于”页面)。

因此,请先验证我的是否有效,然后尝试看看您的做法可能有所不同。 您永远不需要对 CUSTOMCONNSTR_ 前缀做任何假设!

But adding .AddEnvironmentVariables("CUSTOMCONNSTR_") to the configuration builder doesn't work either!

AddEnvironmentVariables with prefix 只是为必须具有指定前缀的环境变量添加限制。它不会改变环境变量。

要从连接字符串配置中检索值,您可以使用如下代码。

Configuration.GetConnectionString("MongoDb:ConnectionString");

对于层次结构设置,请将其添加到应用程序设置中,而不是 Azure 门户上的连接字符串。

How should I now read in these connection strings using the ConfigurationBuilder?

作为解决方法,您可以在获取连接字符串后重新添加 EnvironmentVariable 并重建 ConfigurationBuilder。以下代码供您参考。

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)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
    //Add EnvironmentVariable and rebuild ConfigurationBuilder
    Environment.SetEnvironmentVariable("MongoDb:ConnectionString", Configuration.GetConnectionString("MongoDb:ConnectionString"));
    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}