Gaurav Mantri
Gaurav Mantri

Reputation: 136306

Unable to read settings from Azure App Config Service

I have a working Web API in .Net 7. The Web API reads the configuration settings from appsettings.json local file and it is all working great.

Now I want to use Azure App Configuration service to store the settings. I created an Azure App Configuration service in my Azure Subscription and uploaded the local appsettings.json file. I can see all my settings there so importing also worked. While importing, I chose to use __ as the delimiter.

Now I made the following code changes in my Program.cs to read the settings from Azure:

private static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            _ = webBuilder.UseStartup<Startup>();
            _ = webBuilder.ConfigureAppConfiguration((configurationBuilder) =>
            {
                configurationBuilder.Sources.Clear();
                configurationBuilder.AddAzureAppConfiguration(options =>
                {
                    options.Connect(new Uri("https://myappconfig.azconfig.io"),
                        new DefaultAzureCredential());
                }, false);
                configurationBuilder.Build();
            });
        });
}

Again, this code works fine and no errors are thrown.

However when I try to read the settings in Startup.cs file, I am not getting settings back. For example, here's the code that used to work just fine:

public void ConfigureServices(IServiceCollection services)
{
    //Inject API Settings
    var apiSettings = new ApiSettings();
    Configuration.GetSection("ApiSettings").Bind(apiSettings);
    services.AddSingleton(apiSettings);
    
    // Rest of my code
}

Previously I used to get all the fields of apiSettings getting proper values but now I am getting all of them as null.

Interestingly, when I see the value of Configuration I see all values in Data field there as shown in the screenshot below.

enter image description here

enter image description here

Can anyone please tell me what I am doing wrong?

Upvotes: 1

Views: 2110

Answers (1)

SynerCoder
SynerCoder

Reputation: 12776

According to the documentation:

Hierarchical keys

  • Within the Configuration API, a colon separator (:) works on all platforms.
  • In environment variables, a colon separator may not work on all platforms. A double underscore, __, is supported by all platforms and is automatically converted into a colon :.
  • In Azure Key Vault, hierarchical keys use -- as a separator. The Azure Key Vault configuration provider automatically replaces -- with a : when the secrets are loaded into the app's configuration.

I would suggest importing the configuration using : as a separator. Because they are not environment variables, I would use the default separator.

Upvotes: 3

Related Questions