azureconfigurationapp-configazure-webapps

GetConnectionString using IHostBuilder


(using .NET 6.0)

I used these commands to set a connection string:

but I can't figure out how to retrieve that connection string using IHostBuilder. This returns a null string:

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

debug screen cap


Solution

  • Even Iam getting the user secret value null with the code which you have provided.

    I am able to retrieve the user secret with few changes.

    Thanks @Christian Nagel for the code snippet.

    My Program.cs file

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

    Output:

    enter image description here