【问题标题】:Azure Functions: how do you read the settings in host.json at runtime?Azure Functions:如何在运行时读取 host.json 中的设置?
【发布时间】:2020-01-28 09:16:32
【问题描述】:

有没有办法在运行时读取 host.json 文件中的主机设置? 假设你有一个这样的主机文件:

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

然后如何从 C# 代码中读取 maxConcurrentCalls 设置?

最好也包含默认值。您应该在启动时获得与控制台中打印的相同的值:

[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] }

【问题讨论】:

  • 您可以从local.settings.json 使用它在运行时获取它
  • 我特别想知道host.json的设置。这些不是我的设置,不应该存在于我的 local.settings.json 文件中。
  • 旁注:可以在启动时看到设置(至少在本地),因为它们都打印在终端中。
  • @MikkelR.Lund 这是 host.json 的模板(函数 v2 或更高版本):docs.microsoft.com/en-us/azure/azure-functions/…
  • @BowmanZhu 是的,但这并没有告诉我运行时实际使用的是哪个设置。

标签: c# azure azure-functions settings


【解决方案1】:

这对我有用:

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

【讨论】:

  • 你有完整的例子吗?不确定您 sn-p 的 builder 是什么?
  • @ChrisSmith 我已经编辑了我的答案
【解决方案2】:

这是你想要的吗?

对于您的要求,我认为您可以设计一个函数来读取和解析 json 值。我想你明白host.json文件的格式是固定的,所以我可以在这里举一个简单的例子:

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

结果:

你可以看到我在host.json中得到了maxConcurrentCalls的值。 Azure Function body 上面的函数部分就是你所需要的。

希望我没有理解错误,希望对您有所帮助。

【讨论】:

  • 这只适用于在 host.json 文件中设置的值,对吧?这些设置确实有默认值,通常不会出现在文件中。
猜你喜欢
  • 2020-11-17
  • 2019-12-30
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2022-11-03
  • 2022-12-03
相关资源
最近更新 更多