是否有一种特殊的方法可以在 Azure 应用程序配置中为 ConnectionStrings 定义键值设置?
我试过使用:
ConnectionStrings:DatabaseKeyName
ConnectionStrings\DatabaseKeyName
使用标准
builder.Configuration.GetConnectionString("DatabaseKeyName")
总是会产生 null
值。使用builder.Configuration["ConnectionStrings:DatabaseKeyName"]
也会导致null
,但是如果我使用不以ConnectionStrings开头的键名(例如Test:ConnectionStrings:DatabaseKeyName
它通过builder.Configuration["Test:ConnectionStrings:DatabaseKeyName"]
作为应用程序设置
ConnectionStrings:DatabaseKeyName
的Null值表示Azure App Config中对ConnectionStrings有一些特殊处理,但我不知道我哪里出错了。 Microsoft 示例页面似乎没有涵盖 ConnectionStrings(除了通过 KeyVault)。
基本上我不想改变这个:
services.AddDbContext<IciContext>(o =>
{
o.UseSqlServer(Configuration.GetConnectionString("DatabaseKeyName"));
});
对此:
services.AddDbContext<IciContext>(o =>
{
o.UseSqlServer(builder.Configuration["DatabaseKeyName"]);
});
我需要从 Azure App Config 模拟的标准应用程序配置连接字符串设置:
{
"ConnectionStrings": {
"DatabaseKeyName": "Data Source=localhost;Initial Catalog=xxxx;Integrated Security=True"
},
在我的机密文件中,它采用这种格式(不适用于 Azure App Config):
{
"ConnectionStrings:DatabaseKeyName": "Server=xxxx;Database=xxxx;User ID=xxxx;Password=xxxx"
}
要从 Azure App Configuration 获取连接字符串,请检查以下过程。
安装 NuGet 包
Microsoft.Azure.AppConfiguration.AspNetCore
最新版本以添加 AddAzureAppConfiguration
并读取键值。
要在本地读取Azure App Configuration,我们需要设置secret manager来存储连接字符串。
dotnet user-secrets init
以上命令启用秘密存储并在您的应用程序的
.csproj
中设置秘密ID。
在Program.cs中,添加以下代码
var myAppConn= builder.Configuration.GetConnectionString("AppConfig");
输出:
如MSDoc中所述,对于部署在Azure App Service中的应用程序,建议将连接字符串存储在
Configuration
部分=>Application Settings
=>Connection Strings
部署的应用程序。
是否有一种特殊的方法可以在 Azure App Configuration 中为 ConnectionStrings 定义键值设置?
在 Azure App Configuration =>
*YourAppConfiguration*
=> 点击 Configuration explorer
在 Operations 下 => 点击 Create
=> Key-value
在Program.cs中,添加以下代码
var myconn = builder.Configuration.GetConnectionString("AppConfig");
builder.Host.ConfigureAppConfiguration(builder =>
{
builder.AddAzureAppConfiguration(myconn);
})
.ConfigureServices(services =>
{
services.AddControllersWithViews();
});
在任何
cshtml
文件中,添加以下代码
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<h1>@Configuration["MyConnection"]</h1>
Output for Key-Value from AppConfiguration:
是的,有一种特殊的方法可以在 Azure App Configuration 中为连接字符串定义键值设置。连接字符串设置的密钥格式应为:
ConnectionStrings:<connection-string-name>
替换为您的连接字符串的名称。
例如,如果您的 Azure 应用程序配置实例中有一个名为“MyDbConnection”的连接字符串,则设置的键应该是:
ConnectionStrings:MyDbConnection
要在代码中检索连接字符串,可以使用 IConfiguration 接口的 GetConnectionString() 方法:
var connectionString = configuration.GetConnectionString("MyDbConnection");
请注意,GetConnectionString() 方法会自动查找具有以“ConnectionStrings:”开头的键的设置。如果使用不同的前缀,则需要在检索连接字符串时在密钥中指定前缀。
例如,如果您使用“Test:ConnectionStrings:MyDbConnection”键定义连接字符串设置,则可以按如下方式检索连接字符串:
var connectionString = configuration.GetConnectionString("Test:ConnectionStrings:MyDbConnection");