5

Is there a way to read the host settings in the host.json file at runtime? Say you have a host file like this:

{
  "version": "2.0",
  "extensions": {
    "serviceBus": {
      "messageHandlerOptions": {
        "maxConcurrentCalls": 16
      }
    }
  }
}

How do you then read the maxConcurrentCalls setting from your C# code?

It would be preferred if the default values were included too. You should get the same values as printed in the console on startup:

[28-01-2020 09:16:06] LoggerFilterOptions
[28-01-2020 09:16:06] {
[28-01-2020 09:16:06]   "MinLevel": "None",
[28-01-2020 09:16:06]   "Rules": [
[28-01-2020 09:16:06]     {
[28-01-2020 09:16:06]       "ProviderName": null,
[28-01-2020 09:16:06]       "CategoryName": null,
[28-01-2020 09:16:06]       "LogLevel": null,
[28-01-2020 09:16:06]       "Filter": "<AddFilter>b__0"
[28-01-2020 09:16:06]     },
[28-01-2020 09:16:06]     {
[28-01-2020 09:16:06]       "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
[28-01-2020 09:16:06]       "CategoryName": null,
[28-01-2020 09:16:06]       "LogLevel": "None",
[28-01-2020 09:16:06]       "Filter": null
[28-01-2020 09:16:06]     },
[28-01-2020 09:16:06]     {
[28-01-2020 09:16:06]       "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
[28-01-2020 09:16:06]       "CategoryName": null,
[28-01-2020 09:16:06]       "LogLevel": null,
[28-01-2020 09:16:06]       "Filter": "<AddFilter>b__0"
[28-01-2020 09:16:06]     }
[28-01-2020 09:16:06]   ]
[28-01-2020 09:16:06] }
[28-01-2020 09:16:06] FunctionResultAggregatorOptions
[28-01-2020 09:16:06] {
[28-01-2020 09:16:06]   "BatchSize": 1000,
[28-01-2020 09:16:06]   "FlushTimeout": "00:00:30",
[28-01-2020 09:16:06]   "IsEnabled": true
[28-01-2020 09:16:06] }
[28-01-2020 09:16:06] SingletonOptions
[28-01-2020 09:16:06] {
[28-01-2020 09:16:06]   "LockPeriod": "00:00:15",
[28-01-2020 09:16:06]   "ListenerLockPeriod": "00:00:15",
[28-01-2020 09:16:06]   "LockAcquisitionTimeout": "10675199.02:48:05.4775807",
[28-01-2020 09:16:06]   "LockAcquisitionPollingInterval": "00:00:05",
[28-01-2020 09:16:06]   "ListenerLockRecoveryPollingInterval": "00:01:00"
[28-01-2020 09:16:06] }
[28-01-2020 09:16:06] ServiceBusOptions
[28-01-2020 09:16:06] {
[28-01-2020 09:16:06]   "PrefetchCount": 0,
[28-01-2020 09:16:06]   "MessageHandlerOptions": {
[28-01-2020 09:16:06]     "AutoComplete": true,
[28-01-2020 09:16:06]     "MaxAutoRenewDuration": "00:05:00",
[28-01-2020 09:16:06]     "MaxConcurrentCalls": 192
[28-01-2020 09:16:06]   },
[28-01-2020 09:16:06]   "SessionHandlerOptions": {
[28-01-2020 09:16:06]     "AutoComplete": true,
[28-01-2020 09:16:06]     "MaxAutoRenewDuration": "00:05:00",
[28-01-2020 09:16:06]     "MaxConcurrentSessions": 2000,
[28-01-2020 09:16:06]     "MessageWaitTimeout": "00:01:00"
[28-01-2020 09:16:06]   },
[28-01-2020 09:16:06]   "BatchOptions": {
[28-01-2020 09:16:06]     "MaxMessageCount": 1000,
[28-01-2020 09:16:06]     "OperationTimeout": "00:01:00",
[28-01-2020 09:16:06]     "AutoComplete": true
[28-01-2020 09:16:06]   }
[28-01-2020 09:16:06] }
[28-01-2020 09:16:06] HttpOptions
[28-01-2020 09:16:06] {
[28-01-2020 09:16:06]   "DynamicThrottlesEnabled": false,
[28-01-2020 09:16:06]   "MaxConcurrentRequests": -1,
[28-01-2020 09:16:06]   "MaxOutstandingRequests": -1,
[28-01-2020 09:16:06]   "RoutePrefix": "api"
[28-01-2020 09:16:06] }
6
  • You can use it from local.settings.json for getting it in runtime Commented Jan 28, 2020 at 10:47
  • I specifically want to know the settings from host.json. These are not my settings and shouldn't live in my local.settings.json file. Commented Jan 28, 2020 at 11:35
  • Side note: it is possible to see the settings (at least locally) on startup, as they are all printed in the terminal. Commented Jan 28, 2020 at 12:57
  • @MikkelR.Lund Here is a template for host.json(Function v2 or later): learn.microsoft.com/en-us/azure/azure-functions/… Commented Feb 10, 2020 at 13:50
  • @BowmanZhu Right, but that doesn't show me which setting is actually being used on runtime. Commented Feb 10, 2020 at 15:41

2 Answers 2

3

This works for me:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        var config = builder.GetContext().Configuration;
        string maxConcurrentCalls = config.GetSection("AzureFunctionsJobHost:extensions:serviceBus:messageHandlerOptions:maxConcurrentCalls").Value;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Do you have a full example of this? Not sure what builder is from you snippet?
Need to add annotation for this to work: [assembly: FunctionsStartup(typeof(MyNamespace.Startup))] per docs
This doesn't appear to work in .net6.0
0

Is this what you want?

For your requirements, I think you can design a function to read and parse the json value. I think you understand that the format of the host.json file is fixed, so I can give a simple example here:

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 Newtonsoft.Json.Linq;
using System.Text;

namespace HttpTrigger
{
    public static class Function1
    {
        public static string GetFileJson(string filepath)
        {
            string json = string.Empty;
            using (FileStream fs = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }
        //Read Json Value
        public static string ReadJson()
        {
            string jsonfile = "host.json";
            string jsonText = GetFileJson(jsonfile);
            JObject jsonObj = JObject.Parse(jsonText);
            string value = ((JObject)jsonObj["extensions"])["serviceBus"]["messageHandlerOptions"]["maxConcurrentCalls"].ToString();
            return value;
        }
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string value = ReadJson();

            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;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body" + value);
        }
    }
}

Result:

enter image description here

You can see that I got the value of maxConcurrentCalls inside host.json. The function part above the Azure Function body is what you need.

1 Comment

This would only work with values set in the host.json file, right? The settings do have default values, which normally won't be present in the file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.