我们将一些敏感 key 和连接字符串存储在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_")
添加到配置生成器也不起作用! 最佳答案
带前缀的AddEnvironmentVariables只会为必须带有指定前缀的环境变量添加一个限制。它不会更改环境变量。
要从连接字符串配置中检索值,可以使用以下代码。
Configuration.GetConnectionString("MongoDb:ConnectionString");
对于层次结构设置,请将其添加到应用程序设置中,而不要添加到Azure门户上的连接字符串。
解决方法是,在获得连接字符串后,可以重新添加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();
}