【问题标题】:Connecting Entity Framework to Key Vault with Package Manager Console使用包管理器控制台将实体框架连接到 Key Vault
【发布时间】:2019-12-15 07:40:00
【问题描述】:

我将 appSettings.config 更改为不再有连接字符串,因为它们现在都在 Azure Key Vault 中。我能够连接没有问题,但是现在当我尝试使用 EF 代码创建数据库时,首先使用以下方法在新的 azure db 中迁移:

添加迁移初始创建

我收到错误:

Value cannot be null.
Parameter name: connectionString

Startup.cs

   public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add functionality to inject IOptions<T>
        services.AddOptions();

        // Other configurations here such as for Blob and Notification hub
        //
        //

        services.AddDbContext<ObContext>(opt =>
            opt.UseSqlServer(Configuration["obdbqauser"]));

我的 Program.cs 看起来像这样

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
            {
                //TODO: Seperatre dev and pro - if (context.HostingEnvironment.IsProduction())
                var buildConfig = config.Build();
            //Create Managed Service Identity token provider
            var tokenProvider = new AzureServiceTokenProvider();

            //Create the Key Vault client
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(
                    tokenProvider.KeyVaultTokenCallback));

            config.AddAzureKeyVault(
                $"https://{buildConfig["VaultName"]}.vault.azure.net/",
                keyVaultClient,
                new DefaultKeyVaultSecretManager());
        })

【问题讨论】:

  • 你的Program.cs是什么样的?
  • 您是否尝试过将 appsettings.json 设置为复制到输出文件夹?

标签: entity-framework azure asp.net-core .net-core azure-keyvault


【解决方案1】:

以下是如何将 Key Vault 配置为 ASP.NET Core 2.x 中的配置源的示例:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureAppConfiguration((ctx, builder) =>
        {
            //Build the config from sources we have
            var config = builder.Build();
            //Add Key Vault to configuration pipeline
            builder.AddAzureKeyVault(config["KeyVault:BaseUrl"]);
        })
        .Build();

配置如下:

services.AddDbContext<dbContext>(async options => 
        {
            var keyVaultUri = new Uri("https://xxxxxxxxx.vault.azure.net/");
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            SecretBundle connectionStringSecret = await keyVaultClient.GetSecretAsync(keyVaultUri + "secrets/DBConnectionString");
            options.UseSqlServer(connectionStringSecret.Value);
        });

您需要 Microsoft.Extensions.Configuration.AzureKeyVault 来获取 Key Vault 的配置提供程序。

Key Vault 中的机密命名很重要。例如,我们将覆盖以下连接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "..."
  }
}

您必须创建一个名为 ConnectionStrings--DefaultConnection 的密钥,并将连接字符串作为值。

然后在配置时,您只需使用 Configuration["ConnectionStrings:DefaultConnection"] 来获取连接字符串。如果添加了 Key Vault 配置并且找到了具有正确名称的机密,它将来自 Key Vault。

供参考,请看这个link。

https://entityframeworkcore.com/knowledge-base/53103236/azure-keyvault-for-dbcontext---no-database-provider-has-been-configured-for-this-dbcontext-

希望对你有帮助。

【讨论】:

  • 我有大部分代码,我会看看我缺少什么。我更新了我的帖子以包含我的 Program.cs 代码。我的主要问题是应用程序可以工作并加载数据库但是在包管理器控制台中使用“添加迁移”时出现错误
  • 好的,如果您需要任何其他帮助,请告诉 mw。
  • 这不需要每次解析 DbContext 时都调用 keyvaukt 吗?即...如果您在控制器构造函数中注入 DbContext,则每次构造 webapi 控制器?
  • 有没有办法在从 keyvault 中检索连接字符串后将其缓存到 IOptions 或某个单例对象中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 2013-02-18
  • 2019-04-25
  • 2020-03-04
相关资源
最近更新 更多