Azure Functions - 添加设置数组?

Azure Functions - Adding array of settings?

所以我的 Azure Functions 在本地读取一组设置并对每个对象执行一些逻辑。 我的local.settings.json在下面。

我可以在 Portal 设置中添加单数 Settings 键,但是添加 projects 等数组的最佳方法是什么?我可以简单地在我的项目中包含另一个 JSON 文件吗?可能是个愚蠢的问题,但到目前为止还没有找到答案。

{
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsSecretStorageType": "files",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "PersonalAccessToken": "..."
  },
  "Settings": {
    "url": "https://dev.azure.com/myproject",
    "genericProjectName": "myproject",
    "genericWikiName": "myproject.wiki",
    "projects": [
      {
        "parentPagePath": "/Release notes",
        "name": "Project 1",
        "wikiName": "Project-1.wiki",
        "leasing": true
      }
      {
        "parentPagePath": "/Release notes",
        "name": "Project-2",
        "wikiName": "Project-2.wiki",
        "leasing": true
      }
    ]
  }
}

不,添加数组是不可能的。原因是因为源代码的实现将local.settings.json文件读入环境变量。具体实现如下:

        public AppSettingsFile(string filePath)
        {
            _filePath = filePath;
            try
            {
                var content = FileSystemHelpers.ReadAllTextFromFile(_filePath);
                var appSettings = JsonConvert.DeserializeObject<AppSettingsFile>(content);
                IsEncrypted = appSettings.IsEncrypted;
                Values = appSettings.Values;
                ConnectionStrings = appSettings.ConnectionStrings;
                Host = appSettings.Host;
            }
            catch
            {
                Values = new Dictionary<string, string>();
                ConnectionStrings = new Dictionary<string, string>();
                IsEncrypted = true;
            }
        }

        public bool IsEncrypted { get; set; }
        public Dictionary<string, string> Values { get; set; } = new Dictionary<string, string>();
        public Dictionary<string, string> ConnectionStrings { get; set; } = new Dictionary<string, string>();

详细代码请看这里link:https://github.com/Azure/azure-functions-core-tools/blob/653796ce5d0b5ae9bfd9ecf4073ea1cd010f295e/src/Azure.Functions.Cli/Common/SecretsManager.cs

可以发现Setting和Connecting String从设计之初就是目录类型。不支持数组。

所以,您有两种方法来附加您的目标。

第一种方式,改变结构。

  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsSecretStorageType": "files",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "PersonalAccessToken": "...",
    "projects1-parentPagePath": "/Release notes",
    "projects1-name": "Project 1",
    "projects1-wikiName": "Project-1.wiki",
    "projects1-leasing": true,
    "projects2-parentPagePath": "/Release notes",
    "projects2-name": "Project-2",
    "projects2-wikiName": "Project-2.wiki",
    "projects2-leasing": true
  }

第二种方式,自己设计代码。

您可以创建自己的 json 文件并填写您想要的代码。然后将其属性中的副本属性更改为copy if newer.

那你就可以设计自己的代码来读取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 = "custom.json";
            string jsonText = GetFileJson(jsonfile);
            JObject jsonObj = JObject.Parse(jsonText);
            string value = ((JObject)jsonObj["Settings"])["projects"]["parentPagePath"].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);
        }
    }
}