Asp.net core 使用ConfigurationBuilder检索Web应用程序连接字符串
我们将一些敏感密钥和连接字符串存储在Web App应用程序设置下的连接字符串部分中: 我们使用Asp.net core 使用ConfigurationBuilder检索Web应用程序连接字符串,asp.net-core,asp.net-core-mvc,azure-web-app-service,asp.net-core-1.0,azure-app-service-plans,Asp.net Core,Asp.net Core Mvc,Azure Web App Service,Asp.net Core 1.0,Azure App Service Plans,我们将一些敏感密钥和连接字符串存储在Web App应用程序设置下的连接字符串部分中: 我们使用ConfigurationBuilder检索配置设置: Configuration = new ConfigurationBuilder() .SetBasePath(environment.ContentRootPath) .AddEnvironmentVariables() .Build(); 我本希望AddEnvironmentVariables()能够获取这些连接字符
ConfigurationBuilder
检索配置设置:
Configuration = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddEnvironmentVariables()
.Build();
我本希望AddEnvironmentVariables()
能够获取这些连接字符串,但事实并非如此。请注意,如果您在Web应用中将这些值设置为“应用程序设置”,则此操作不起作用
在更仔细的检查下(使用Kudu控制台),我发现为这些连接字符串设置的环境变量在键名前加了CUSTOMCONNSTR_uu前缀:
CUSTOMCONNSTR_MongoDb:ConnectionString=...
CUSTOMCONNSTR_Logging:ConnectionString=...
CUSTOMCONNSTR_ApplicationInsights:ChronosInstrumentationKey=...
现在如何使用ConfigurationBuilder
读取这些连接字符串
编辑:
我发现存在一个方便的AddEnvironmentVariables
重载,带有前缀
参数,描述如下:
// prefix:
// The prefix that environment variable names must start with. The prefix will be
// removed from the environment variable names.
但是将
.AddEnvironmentVariables(“CUSTOMCONNSTR”)
添加到配置生成器也不起作用 它应该可以正常工作,在我的示例应用程序中也可以。具体而言:
已定义连接字符串MyDatabase
- 它被使用
- 如果您在Azure Portal中定义了
conn字符串,您将在运行时看到新值(转到“关于”页面)MyDatabase
CUSTOMCONNSTR\uu
前缀进行任何假设强>
但是将.AddEnvironmentVariables(“CUSTOMCONNSTR”)添加到配置生成器也不起作用
AddEnvironmentVariables with prefix只需为必须使用指定前缀的环境变量添加一个限制。它不会改变环境变量
要从连接字符串配置中检索值,可以使用以下代码
Configuration.GetConnectionString("MongoDb:ConnectionString");
对于层次结构设置,请将其添加到应用程序设置,而不是Azure portal上的连接字符串
现在如何使用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();
}
我没有将它们存储在JSON文件中——只存储在Web应用程序设置中(因此需要从环境变量中检索它们)。为了清晰起见,我已经从上面的配置中删除了AddJsonFile()。这是关于佩奇的吗?我确实可以在env vars中看到连接字符串,但只能使用带前缀的键。它在我的应用程序中工作,即使没有在JSON中设置它(即仅Azure连接字符串)。运行时,顶部有一个关于链接。