0

I have a C# function app written in .NET 6.0 and I want to read a collection of settings from the local.settings.json file. Here is my startup file that I want to read my settings so I can access them later in my application:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        BindAndRegisterStronglyTypedConfig(builder);
    }

    private void BindAndRegisterStronglyTypedConfig(IFunctionsHostBuilder builder)
    {
        var products = new Products();
        builder.GetContext().Configuration.Bind(nameof(Products), products);
        builder.Services.AddSingleton(products);
    }
}

Then in my local.settings.json file I have the products that I want to read:

{
  "Values": {
    "Products": [
      {
        "ProductId": "#",
        "Title": "#"
      },
      {
        "ProductId": "#",
        "Title": "#"
      }
    ]    
  }
}

The models the values should bind to:

public class Products
{
    public readonly List<Product> products = new List<Product>();
}

public class Product
{
    public string ProductId { get; set; }
    public string Title { get; set; }
}

Anybody understand what I've done wrong, I get no error just a null value for collection?

stuartd
  • 70,509
  • 14
  • 132
  • 163
Martin Cooke
  • 526
  • 1
  • 4
  • 18

1 Answers1

0

Check if the below findings help the requirement:

read my local settings so I can access them later in my application:

One of the ways is in the Same Function Trigger Code, you can fetch the Configuration settings using Configuration class. Below is the sample code for it, taken from the SO reference 70576009

public static object GetAppSettings(IConfiguration configuration, ILogger log)
{
    string localsetting1 = configuration.GetValue("Setting1");
}

And another workaround is to Check the local.settings.json configuration code should be in clear format with the Parent-child format where child will be in key-value relationship which is similar to your given configuration and that configuration settings fetching process code and the format of local.settings.json is given in the SO#72786915 by the user @SimonPrice.

Your local.settings.json code is same given in the above reference if it is formatted such as:

{
  "Values": {
    "Products:ProductId": "#",
    "Products:Title": "#",
    "Products:ProductId2": "#",
    "Products:Title2": "#",
     }
}
Pravallika KV
  • 2,415
  • 2
  • 2
  • 7