azure 使用IHostBuilder获取连接字符串

kadbb459  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(92)

(使用.NET 6.0)
我使用这些命令来设置连接字符串:

  • dotnet user-secrets init
  • dotnet user-secrets set ConnectionStrings:AppConfig“{myconnectionstring}”

但我不知道如何使用IHostBuilder检索该连接字符串。这将返回一个空字符串:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
            {
                configurationBuilder.AddAzureAppConfiguration(options =>
                {
                    var azureAppConfigConnectionString = hostingContext.Configuration.GetConnectionString("AppConfig");

brgchamk

brgchamk1#

即使我得到的用户秘密值空与您提供的代码。
我能够检索用户的秘密与几个变化。
感谢@Christian内格尔提供的代码片段。

  • 添加configurationBuilder.Build();,然后从变量中检索值。
  • 我的Program.cs文件 *
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using System;

public class Program
{
   public static void Main(string[] args)
   {
       CreateHostBuilder(args).Build().Run();
   }

   private static IHostBuilder CreateHostBuilder(string[] args) =>
       Host.CreateDefaultBuilder(args)

           .ConfigureWebHostDefaults(webBuilder =>
           {
               webBuilder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
               {
                   var mysettings = configurationBuilder.Build();
                   var azureAppConfigConnectionString = mysettings.GetConnectionString("AppConfig");

                   configurationBuilder.AddAzureAppConfiguration(options =>
                   {
                       options.Connect(azureAppConfigConnectionString);                              
                   });
               })
               .UseStartup<Startup>();
           });
}
  • 输出:*

相关问题