Azure函数:如何在运行时读取host.json中的设置?

问题描述 投票:0回答:1

是否可以在运行时读取host.json文件中的主机设置?假设您有一个这样的主机文件:

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

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

c# azure azure-functions settings
1个回答
0
投票

这是您想要的吗?

根据您的要求,我认为您可以设计一个函数来读取和解析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);
        }
    }
}

结果:

enter image description here

[您可以看到我在host.json中获得了maxConcurrentCalls的值。您需要的是Azure Function主体上方的函数部分。

如果有任何疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.