5

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

连接字符串 Azure Web App

我们使用以下方法检索配置设置ConfigurationBuilder

Configuration = new ConfigurationBuilder()
    .SetBasePath(environment.ContentRootPath)
    .AddEnvironmentVariables()
    .Build();

我本来希望AddEnvironmentVariables()拿起这些连接字符串,但事实并非如此。请注意,如果您在 Web 应用程序中将这些值设置为“应用程序设置”,这确实有效。

经过仔细检查(使用 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_")到配置生成器也不起作用!

4

2 回答 2

2

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

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

因此,首先要验证我的工作是否有效,并尝试看看您可能会做哪些不同的事情。您永远不需要对CUSTOMCONNSTR_前缀做出任何假设!

于 2017-04-24T16:58:50.830 回答
2

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

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

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

Configuration.GetConnectionString("MongoDb:ConnectionString");

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

我现在应该如何使用 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();
}
于 2017-04-25T08:27:22.853 回答