Azure App Config中JSON键值对读取不符合预期问题排查
我正在开发一个Azure Function,需要接收JSON输入并触发涵盖本地与Azure DevOps的混合CI/CD管道。为实现配置与代码分离,计划用Azure App Configuration存储配置,让Function根据JSON输入触发对应管道。但作为App Config新手,遇到了问题:
我把TestStructure.json里的JSON对象通过Azure CLI导入App Config,命令返回和Azure门户显示键为TestStructure.Repository1等,对应值是嵌套JSON字符串,符合预期。但用.NET 6控制台应用读取时,config["TestStructure.Repository1"]返回null。调试发现config对象里的实际键是TestStructure.Repository1:RepositoryName格式,不是预期的键,导致无法正常读取。
相关配置与代码
TestStructure.json内容
{ "TestStructure": { "Repository1": { "RepositoryName": "Repository1", "RepositoryUrl": "https://url.repository1.com/" }, "Repository2": { "RepositoryName": "Repository2", "RepositoryUrl": "https://url.repository2.com/" }, "Repository3": { "RepositoryName": "Repository3", "RepositoryUrl": "https://url.repository3.com/" } } }
导入命令
az appconfig kv import -n <myAppConfigName> -s file --format json --path "C:\workspace\TestStructure.json" --content-type "application/json" --separator . --depth 2
读取代码
using Microsoft.Extensions.Configuration; var config = new ConfigurationBuilder() .AddAzureAppConfiguration("MyConnectionString") .Build(); var repository = config["TestStructure.Repository1"] // 返回null
问题原因
你使用的--depth 2参数会让Azure CLI将JSON结构拆解到第二层,把TestStructure.Repository1下的子属性(RepositoryName、RepositoryUrl)拆分成独立的键值对,键格式为TestStructure.Repository1:RepositoryName(冒号是.NET配置系统的默认层级分隔符),而不是将TestStructure.Repository1作为一个整体键存储对应的嵌套JSON值。
虽然Azure门户显示的键是TestStructure.Repository1,但实际上CLI的--depth参数已经将嵌套结构扁平化了,导致.NET配置系统读取到的是拆解后的子键,而非完整的嵌套JSON块。
解决方法
方法1:调整导入命令的--depth参数
如果希望将TestStructure.Repository1这类层级作为整体存储为JSON字符串,需要将--depth设置为1,这样只会拆解到第一层,保留第二层的完整JSON结构:
az appconfig kv import -n <myAppConfigName> -s file --format json --path "C:\workspace\TestStructure.json" --content-type "application/json" --separator . --depth 1
导入后,TestStructure.Repository1对应的就是完整的嵌套JSON字符串,此时用config["TestStructure.Repository1"]就能正确读取到值。
方法2:读取拆解后的子键
如果需要保留当前的扁平化结构,可以直接通过子键读取对应值:
var repoName = config["TestStructure.Repository1:RepositoryName"]; var repoUrl = config["TestStructure.Repository1:RepositoryUrl"];
或者绑定到实体类,更方便地读取:
public class RepositoryConfig { public string RepositoryName { get; set; } public string RepositoryUrl { get; set; } } var repoConfig = config.GetSection("TestStructure.Repository1").Get<RepositoryConfig>();
内容的提问来源于stack exchange,提问作者kdhansen

