How to get multiple values of same variable in the function class from local.settings.json file?

krishna572 886 Reputation points
2023-07-21T06:17:37.2866667+00:00

local.settings.json:

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "FUNCTIONS_WORKER_RUNTIME": "dotnet",
      "toAddress": [
        {
          "mail1": "******@gmail.com",
          "mail2": "******@hotmail.com",
          "mail3": "******@honda.com"
        }
      ]
    }
}


Function Class:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Configuration;
using Microsoft.Extensions.Configuration;

namespace ArrayVarPoC
{
    public class Function1
    {

        private readonly IConfiguration _config;
        public Function1(IConfiguration config)
        {

            _config = config;

        }
        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string[] toAddress = _config.GetValue<string[]>("toAddress");
            log.LogInformation($"[{toAddress.ToString}]");
            

            string responseMessage = "Hello Fish, This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

I'm able to get the single value of the variable defined in local.settings.json but not the array variable values.

I tried to get the array variable values defined the local.settings.json file to the function class but not sure how to write the code for it.

Could anyone help me how to get this?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,703 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,419 questions
{count} votes

2 answers

Sort by: Most helpful
  1. MuthuKumaranMurugaachari-MSFT 22,421 Reputation points
    2023-07-25T20:29:17.9466667+00:00

    billa Thanks for posting your question in Microsoft Q&A. As per doc: Local settings file, Values must be strings and not JSON objects or arrays.

    User's image

    However, you can define the values like below in the local.settings.json file (also application setting in azure; use__ for Linux instead of :) and use dependency injection to bind the values.

    Local.settings.json

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet",
        "ToAddress:0:Mail1": "******@gmail.com",
        "ToAddress:0:Mail2": "******@hotmail.com",
        "ToAddress:0:Mail3": "******@honda.com"
      }
    }
    

    Startup.cs (Check Use dependency injection in .NET Azure Functions for detailed info about the dependency injection)

    [assembly: FunctionsStartup(typeof(HttpTriggerParse.Startup))]
    namespace HttpTriggerParse
    {
        public class Startup : FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
    
                builder.Services.AddOptions<List<MailAddress>>()
                    .Configure<IConfiguration>((settings, configuration) =>
                    {
                        configuration.GetSection("ToAddress").Bind(settings);
                    });
            }
        }
    }
    

    Function1.cs

    public class Function1
        {
            private List<MailAddress> ToAddress;
            public Function1(IOptions<List<MailAddress>> mailAddresses)
            {
                ToAddress = mailAddresses.Value;
            }
    
            [FunctionName("Function1")]
            public async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
    
                string name = req.Query["name"];
    
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;
    
                string responseMessage = string.IsNullOrEmpty(name)
                    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                    : $"Hello, {name}. This HTTP triggered function executed successfully.";
    
                return new OkObjectResult(responseMessage);
            }
        }
    

    Output:
    User's image

    Also, check out similar discussion in SO thread and that might assist you with some questions. I hope this helps and let me know if you have any questions.


    If you found the answer to your question helpful, please take a moment to mark it as "Yes" for others to benefit from your experience. Or simply add a comment tagging me and would be happy to answer your questions

    1 person found this answer helpful.
    0 comments No comments

  2. Jiale Xue - MSFT 49,831 Reputation points Microsoft External Staff
    2023-07-21T08:04:28.7833333+00:00

    Hi @krishna572 , Welcome to Microsoft Q&A.

    You just need to use System.Text.Json to parse the json file.

    You can parse it through the json file, and I will directly use json string to demonstrate:

    using System;
    using System.Collections.Generic;
    using System.Text.Json;
    namespace _7_21_x
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                string json = @"
            {
                ""IsEncrypted"": false,
                ""Values"": {
                    ""AzureWebJobsStorage"": ""UseDevelopmentStorage=true"",
                    ""FUNCTIONS_WORKER_RUNTIME"": ""dotnet"",
                    ""toAddress"": [
                        {
                            ""mail1"": ""******@gmail.com"",
                            ""mail2"": ""******@hotmail.com"",
                            ""mail3"": ""******@honda.com""
                        }
                    ]
                }
            }";
    
                // Deserialize the JSON to the RootObject
                var data = JsonSerializer.Deserialize<RootObject>(json);
                // Get all addresses
                var allAddresses = data.Values.toAddress;
                foreach (var address in allAddresses)
                {
                    // Output mail attributes and their values
                    foreach (var property in address.EnumerateObject())
                    {
                        if (property.Value.ValueKind == JsonValueKind.String && property.Name.StartsWith("mail"))
                        {
                            Console.WriteLine($"{property.Name}: {property.Value.GetString()}");
                        }
                    }
                    Console.WriteLine();
                }
                Console.ReadLine();
            }
        }
        public class RootObject
        {
            public bool IsEncrypted
            {
                get;
                set;
            }
            public ValuesObject Values
            {
                get;
                set;
            }
        }
        public class ValuesObject
        {
            public string AzureWebJobsStorage
            {
                get;
                set;
            }
            public string FUNCTIONS_WORKER_RUNTIME
            {
                get;
                set;
            }
            public List<JsonElement> toAddress
            {
                get;
                set;
            }
        }
    }
    

    User's image

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.