Retrieving Web App connection strings using ConfigurationBuilder

Dav*_*New 5 azure-web-sites asp.net-core-mvc azure-app-service-plans asp.net-core asp.net-core-1.0

We are storing some of our sensitive keys and connection strings in the Connection strings section under the Web App application settings:

连接字符串Azure Web App

We retrieve configuration settings using the ConfigurationBuilder:

Configuration = new ConfigurationBuilder()
    .SetBasePath(environment.ContentRootPath)
    .AddEnvironmentVariables()
    .Build();
Run Code Online (Sandbox Code Playgroud)

I would have expected AddEnvironmentVariables() to pick up these connection strings, but it doesn't. Note that this does work if you set these values as "App settings" in the Web App.

Under closer inspection (using the Kudu console) I found that the environment variables being set for these connections strings have CUSTOMCONNSTR_ prefixed to the key name:

CUSTOMCONNSTR_MongoDb:ConnectionString=...
CUSTOMCONNSTR_Logging:ConnectionString=...
CUSTOMCONNSTR_ApplicationInsights:ChronosInstrumentationKey=...
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

//   prefix:
//     The prefix that environment variable names must start with. The prefix will be
//     removed from the environment variable names.
Run Code Online (Sandbox Code Playgroud)

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

Amo*_*mor 2

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

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

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

Configuration.GetConnectionString("MongoDb:ConnectionString");
Run Code Online (Sandbox Code Playgroud)

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

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

作为解决方法,您可以在获取连接字符串后重新添加环境变量并重建 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();
}
Run Code Online (Sandbox Code Playgroud)