简体   繁体   English

Azure KeyVault for DBContext:“尚未为此DbContext配置数据库提供程序”

[英]Azure KeyVault for DBContext: “No database provider has been configured for this DbContext”

I am building a Web API using .NET Core 2.1. 我正在使用.NET Core 2.1构建Web API。 This will be hosted as an Azure Web App. 这将作为Azure Web App托管。 I want to keep my database connection string in my Azure Key Vault. 我想将数据库连接字符串保留在我的Azure Key Vault中。 This is the code that I have put in my Startup.cs ConfigureServices method: 这是我放入Startup.cs ConfigureServices方法中的代码:

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);
        });

When I try to make an HTTP Get to my controller that has the dbContext injected into it I get the following error: 当我尝试向已注入dbContext的控制器获取HTTP Get时,出现以下错误:

InvalidOperationException: No database provider has been configured 
for this DbContext. A provider can be configured by overriding the
DbContext.OnConfiguring method or by using AddDbContext on the 
application service provider. If AddDbContext is used, then also 
ensure that your DbContext type accepts a DbContextOptions<TContext> 
object in its constructor and passes it to the base constructor for 
DbContext.

I am assuming that is is because of my use of the async lambda to get the connection string from the Key Vault, however, I'm not sure what to do about it. 我以为那是因为我使用了异步lambda来从Key Vault获取连接字符串,但是,我不确定该怎么做。 Is this the right way to get a connection string from Azure KeyVault for use in the Startup.cs? 这是从Azure KeyVault获取连接字符串以在Startup.cs中使用的正确方法吗? Should I do this a different way? 我应该以其他方式这样做吗? Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

The reason your configuration fails is because the callback is now async void . 配置失败的原因是因为回调现在async void This is not obvious from looking at the lambda, but it is effectively fire and forget. 从lambda看,这并不明显,但实际上是开火而忘了。 When you await the key vault client, it returns from the callback without configuring the provider. 当您等待密钥库客户端时,它会从回调中返回而无需配置提供程序。

As for a solution, I think it is better to add the key vault secrets into the config system so you can use them from there as if they came in from a JSON file or any other source. 至于解决方案,我认为最好将密钥库机密添加到配置系统中,以便您可以从那里使用它们,就像它们是从JSON文件或任何其他来源传入的一样。

I wrote an article on this a while back: https://joonasw.net/view/aspnet-core-azure-keyvault-msi . 我前一段时间写了一篇文章: https : //joonasw.net/view/aspnet-core-azure-keyvault-msi I used managed identity to authenticate in my article, but I see you are using it too :) 我在文章中使用托管身份进行身份验证,但我看到您也在使用它:)

Here is a sample for how you can configure Key Vault as a configuration source in ASP.NET Core 2.x: 以下是有关如何在ASP.NET Core 2.x中将Key Vault配置为配置源的示例:

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();

The sample I have in the article is actually a bit over-verbose as this will use the AzureServiceTokenProvider internally to acquire tokens. 我在本文中使用的示例实际上有点冗长,因为这将在内部使用AzureServiceTokenProvider来获取令牌。

You'll need Microsoft.Extensions.Configuration.AzureKeyVault to get the configuration provider for Key Vault. 您需要Microsoft.Extensions.Configuration.AzureKeyVault才能获取Key Vault的配置提供程序。

The secret naming in Key Vault will matter. Key Vault中的秘密命名至关重要。 For example, we will override the following connection string: 例如,我们将覆盖以下连接字符串:

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

You would have to create a secret named ConnectionStrings--DefaultConnection with the connection string as the value. 您将必须使用连接字符串作为值来创建一个名为ConnectionStrings--DefaultConnection的秘密。

Then while configuring you just use Configuration["ConnectionStrings:DefaultConnection"] to get the connection string. 然后在配置时,只需使用Configuration["ConnectionStrings:DefaultConnection"]即可获取连接字符串。 It'll come from Key Vault if Key Vault config was added and a secret with the right name was found. 如果添加了密钥库配置,并且找到了具有正确名称的秘密,它将来自密钥库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尚未为此 DbContext 配置数据库提供程序 - No database provider has been configured for this DbContext InvalidOperationException:没有为此DbContext配置数据库提供程序 - InvalidOperationException: No database provider has been configured for this DbContext InvalidOperationException:没有为此DbContext配置数据库提供程序。 可以通过覆盖DbContext来配置提供程序 - InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext 没有为此 DbContext 配置数据库提供程序。 可以通过覆盖 DbContext.OnConfiguring 来配置提供程序 - No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring 无法解决此错误,“尚未为此 DbContext 配置数据库提供程序” - Cannot solve this error, "No database provider has been configured for this DbContext" InvalidOperationException:没有为此DbContext配置数据库提供程序。 - InvalidOperationException: No database provider has been configured for this DbContext. DotNet Core,没有为此DbContext配置数据库提供程序 - DotNet Core , No database provider has been configured for this DbContext 错误:System.InvalidOperationException:没有为此 DbContext 配置数据库提供程序 - ERROR: System.InvalidOperationException: No database provider has been configured for this DbContext ASP.NET API:尚未为此DbContext配置任何数据库提供程序 - ASP.NET API: No database provider has been configured for this DbContext add-Migration 错误 没有为此 DbContext 配置数据库提供程序 - add-Migration Error No database provider has been configured for this DbContext
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM