简体   繁体   English

使用Package Manager控制台将实体框架连接到Key Vault

[英]Connecting Entity Framework to Key Vault with Package Manager Console

I changed my appSettings.config to no longer have connection strings as they are now all in Azure Key Vault. 我将appSettings.config更改为不再具有连接字符串,因为它们现在都在Azure Key Vault中。 I was able to connect no problem, but now when I try to create the db using EF code first migrations in a new azure db using: 我能够毫无问题地进行连接,但是现在当我尝试使用EF代码创建数据库时,首先使用以下命令在新的Azure数据库中进行迁移:

add-migration InitialCreate add-migration InitialCreate

I am getting the error: 我收到错误消息:

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"]));

My Program.cs looks like this 我的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());
        })

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

and a configuration would be like below: 配置如下所示:

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

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. 如果添加了密钥库配置,并且找到了具有正确名称的秘密,它将来自密钥库。

For reference , please take a look at this link . 作为参考,请查看此链接

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

Hope it helps. 希望能帮助到你。

暂无
暂无

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

相关问题 实体框架包管理器控制台问题 - Entity Framework Package Manager Console question 在项目中管理Entity Framework的程序包管理器控制台命令 - Managing Package Manager Console commands for Entity Framework in project 实体框架程序包管理器控制台命令错误-生成失败 - Entity Framework Package Manager Console Commands Error - failed to build 与程序包管理器控制台中的实体框架相关的项目启动出错 - Error on Project Startup relating to Entity Framework in Package Manager Console 如何在程序包管理器控制台中获取实体框架的可用命令列表 - How to get list of available commands for Entity Framework in package manager console Project X 以框架“.NETStandard”为目标。 实体框架 Package 管理器控制台工具不支持此框架 - Project X targets framework '.NETStandard'. The Entity Framework Package Manager Console Tools don't support this framework 使用包管理器控制台“ Update-Database”等在实体框架中以编程方式连接字符串 - Programmatically connection string in entity framework with package manager console “Update-Database” etc 如何在Package Manager控制台外部运行Entity Framework命令? - How can I run Entity Framework commands outside Package Manager Console? 此版本的Entity Framework核心软件包管理器控制台工具不支持这些类型的项目 - This version of the Entity Framework Core Package Manager Console Tools doesn't support these types of projects 当我在 package 管理器控制台中的 Visual Studio 2013 中安装实体框架时 - When I am installing Entity Framework in Visual Studio 2013 in the package manager console
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM