asp.net-core – 使用ConfigurationBuilder检索Web App连接字符串

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

《asp.net-core – 使用ConfigurationBuilder检索Web App连接字符串》

我们使用ConfigurationBuilder检索配置设置:

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

我本来期望AddEnvironmentVariables()来获取这些连接字符串,但事实并非如此.请注意,如果您在Web App中将这些值设置为“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_”)添加到配置构建器也不起作用!

最佳答案

But adding .AddEnvironmentVariables(“CUSTOMCONNSTR_”) to the configuration builder doesn’t work either!

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

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

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();
}
点赞