我们将一些敏感 key 和连接字符串存储在 Web 应用程序设置下的连接字符串部分中:
我们使用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_")
添加到配置生成器也不起作用!
最佳答案
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?
作为解决方法,您可以在获取连接字符串后重新添加环境变量并重建 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();
}
关于asp.net-core - 使用 ConfigurationBuilder 检索 Web 应用程序连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43592215/