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

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

Connection strings Azure Web App

我们使用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/

相关文章:

c# - 如何为 ASP.NET Core 2 中的所有 Razor 页面添加 .html url 后缀?

azure - 如何在使用 GitHub 作为源代码管理的同时部署 Azure 网站?

azure - 浏览部署在 Azure 中的 Angular 8 应用程序时出错

c# - 如何使用 ASP.Net Core Identity 从登录用户检索 Facebook 个人资料图片?

authentication - ASP Core 向 Auth Token 添加自定义声明

c# - 如何在 ASP.NET Core 7 中以 JSON 形式返回纯字符串

asp.net-core - AspNet5 - Windows 身份验证从声明中获取组名

asp.net-mvc - MVC 6 使用外键编辑模型

php - 让Azure Web应用程序显示php错误

c# - 属性 'x' 不是实体类型 'y' 的导航属性