【问题标题】:Supplying Azure SQL DB connection string for ASP.NET Core MVC & EF Core solution为 ASP.NET Core MVC 和 EF Core 解决方案提供 Azure SQL DB 连接字符串
【发布时间】:2021-11-08 18:50:15
【问题描述】:

我相信我正在遵循 Microsoft 推荐的方法,并且我拥有所需的组件,但不知道如何将它们组合在一起。

我正在使用 Azure 应用程序配置服务来存储密钥保管库密钥(以及其他配置设置),并使用密钥保管库服务来提供包含 Azure SQL Server 用户名/密码的数据库连接字符串)

我有以下单独的工作项目/解决方案 (ASP.NET Core MVC):

  • 具有 Azure SQL DB 功能的可运行的 Azure Web 应用程序,可输出 CRUD 和表数据
  • 一个有效的 Azure Web 应用程序,使用 Azure 应用程序配置为密钥和密钥库输出字符串“秘密”
  • 我已使用托管 ID 访问所有 Azure 资源

使用 测试应用程序,我可以使用 3 个项目文件中的代码从我的 Azure 应用程序配置和 Key Vault 服务中输出虚拟配置数据:

  • Program.cs webBuilder.ConfigureAppConfiguration((context, config)
  • appsettings.json "AzureAppConfigurationEndpoint": "https://xxxxxxxxxx.azconfig.io"
  • /Views/~/razor 页面@Configuration["TestApp:Settings:KeyVaultDbString"]

我的 db app 使用这些文件中的代码访问 db 连接字符串:

  • Startup.cs public void ConfigureServices(IServiceCollection services)
  • appsettings.json"DefaultConnection":"Server=tcp:xxxx.database.windows.net,1433;XXXXXXX"

我想升级我的 db app 以使用 test app 提供的连接字符串配置值。因此计划是:

将测试应用 Program.cs 中的代码合并到数据库应用 Program.cs 中。我认为这没有问题。

public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
     .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureAppConfiguration((context, config) =>
            {
                var settings = config.Build();
                var appConfigurationEndpoint = settings["AzureAppConfigurationEndpoint"];

                config.AddAzureAppConfiguration(options =>
                   {
                       options.Connect(new Uri(appConfigurationEndpoint), new DefaultAzureCredential());

                           options.ConfigureKeyVault(kv =>
                            {
                                kv.SetCredential(new DefaultAzureCredential());
                            });
                   });

                webBuilder.UseStartup<Startup>();
            });
        });

但是。此时我不知道如何访问 Startup.cs 中的["TestApp:Settings:KeyVaultDbString"] 配置数据。提供"KeyVaultDbString" 代替我的"DefaultConnection"

这是现有的代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddControllersWithViews();

    // this code is responsible for login-intercept required for solution
    services.AddAuthorization(options =>
        {
            options.FallbackPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
        });
}

虽然使用 @Configuration["TestApp:Settings:KeyVaultMessage"] 从视图页面访问 Azure 配置数据很容易,但我在 Startup.cs 中配置服务时如何访问?

我已阅读Configuration in ASP.NET Core。我理解以下内容:

  • Azure App Configuration 和 Key Vault 是配置提供程序(如 appsettings、环境变量和命令行中提供的那些)
  • “连接字符串前缀”下的部分是相关的,但没有代码示例
  • 自定义配置提供程序下的部分详细说明了我的情况可能需要的选项构建
  • “启动中的访问配置”和“Razor 页面中的访问配置”下的部分似乎与我使用的语法直接相关。但仍然让我想知道如何将我的字符串与它的标签分开,以便用作我的数据库应用程序的“DefaultConnection”。

任何建议将不胜感激。

【问题讨论】:

  • 我添加了 'Console.WriteLine($"MyKey : {Configuration["TestApp:Settings:KeyVaultDbString"]}");'在 Startup.cs 中,并在 Visual Studio 的“运行您的代码”框中使用我的项目名称运行。这在控制台窗口中产生了正确的输出(我的数据库连接字符串)。我想这是使用它的方法。类似'Configuration.GetConnectionString("TestApp:Settings:KeyVaultDbString")));'在我的 ConfigureServices 方法中。似乎太容易了!

标签: c# asp.net-core configuration credentials azure-keyvault


【解决方案1】:

appsettings.json 中创建以下内容:

{
  "Data": {
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=db;Trusted_Connection=True;"
  }
}

Startup.cs中提供相关的连接字符串。更新 ConfigureServices 方法:

var conn = Configuration.GetConnectionString("DefaultConnection");
  • 在任何使用 Entity Framework Core 的 MVC 应用程序中,DbContext 是在 ConfigureServices 方法中使用依赖注入注入的。

  • 启动类中也需要连接字符串

  • 要从 Startup 类中读取,需要一个 IConfiguration 对象,该对象可以从依赖注入中注入。

  • 要注入Startup 类,开发人员可以使用构造函数或GetConnectionString 方法。 详情请参考Connection Strings: Entity Framework CoreSO

【讨论】:

  • HarshithaVeeramalla-MT 感谢您的意见。但是,也许我的问题并不清楚。我一直在使用 appsettings.json 作为我的数据库连接字符串。我现在想使用 Azure Key Vault 隐藏我的连接字符串。我的问题与在我的启动代码中使用 Azure Key Vault(不是 appsettings.json)中的 db 连接字符串配置有关。无论如何,我理解你在说什么,并认为你给出了很好的建议。
  • @Dave - 我了解到您需要使用 Azure KeyVault 隐藏连接字符串;我建议您使用 2 个解决方案:1) 要将凭据隐藏在 web.config 文件之外并在运行时轻松检索,请使用此 private string CS = ConfigurationManager.ConnectionStrings["mySecretConStr"].ConnectionString; 2) 要在 Azure Key Vault 中添加您的机密,请参阅 this
  • 感谢您的帮助。博客很有用。使用断点查看配置提供程序的建议。我使用 Startup.cs 中的一小部分代码更改了我的问题。根据我是在 appsettings.json 中还是将其存储在 Azure Key Vault 中,访问连接字符串会有所不同。
  • appsettings 中的行是 '.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))' 和 Key Vault '.UseSqlServer(@Configuration["TestApp:Settings:KeyVaultDbConnectionString"])' 我现在通过 Azure 应用配置从 Key Vault 获取我的 localdb 字符串。我认为 appsettings 连接字符串需要配置扩展代码,但因为 Key Vault 只是一个字符串,所以我不使用扩展代码。这些是不可互换的。
  • 如果我的回答对您有帮助,您可以接受它作为答案(单击答案旁边的复选标记,将其从灰色切换为已填充。)。这对其他社区成员可能是有益的。谢谢
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2019-05-13
相关资源
最近更新 更多