【发布时间】:2022-11-03 18:30:56
【问题描述】:
我正在编写一个 .NET Core 6 Web API 并尝试转换为使用密钥保管库。我在CreateAppConfiguration 部分调用AddAzureKeyVault 但我需要在Startup.cs 的ConfigureServices 方法中调整数据库连接字符串,因为这是我们设置服务(包括SQL Server)的地方。即使当我停在ConfigurationServices 内时,我已经超过了AddAzureKeyVault 中的断点,但我看到了appsettings 文件中的原始虚拟值。后来,在我的控制器方法中,它们很好地覆盖在我的appsettings 之上,正如您所期望的那样。
目前,我在那里加载 keyvault 值只是为了使其工作,但必须有一些更好的方法以便更快地加载 keyvault 值 - 有吗?我还能把它放在哪里?
来自 Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config =>
{
...
config.AddAzureKeyVault(new Uri(vaultUrl), credential, new PrefixKeyVaultSecretManager("KVTest"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
来自 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//======================= new key vault stuff ===========================
// The key vault values have NOT been applied yet, so we need to manually grab the DB conn string here
var connString = Configuration.GetConnectionString("InformCoreDbContext");
//^^ I see the dummy string from the appsettings file here
//======================= horrible kludge ===============================
// If I open the keyvault and grab the conn string that works, but
// I shouldn't have to do this here since I'm overloading them at some point
connString = temporaryMachinationsToGrabKeyVaultConnString();
services.AddPooledDbContextFactory<ICAdminContext>(options =>
options.UseSqlServer(connString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure();
}));
注意:我确实阅读了how-to-get-azure-keyvault-key-inside-config,但该解决方案对我不起作用。扩展方法中的配置对象仍然没有加载 keyvault 条目。
【问题讨论】:
标签: sql-server .net-core azure-keyvault