如何通过Microsoft.Extensions.Configuration读取appsettings.json数据?
解决Microsoft.Extensions.Configuration读取appsettings.json数组的问题
看起来你的问题主要来自两个方面:appsettings.json格式错误,以及对GetChildren()返回值的误解,我一步步帮你解决:
1. 先修正appsettings.json的格式
你提供的JSON片段缺少外层的根对象大括号,这会直接导致JSON解析失败,出现Uncaught SyntaxError: Invalid or unexpected token错误。正确的格式应该是:
{ "Test": [ { "A": "101", "B": "6390" }, { "A": "101", "B": "6391" }, { "A": "101", "B": "6392" } ] }
JSON必须有一个顶层对象,所以一定要加上最外层的{}。
2. 正确读取数组的两种方式
方式一:绑定到强类型集合(推荐)
这种方式更简洁易维护,先定义对应的数据模型:
public class TestItem { public string A { get; set; } public string B { get; set; } }
然后通过Get<T>()方法直接将数组绑定到List<TestItem>:
// 假设你已经完成Configuration的构建 var testItems = Configuration.GetSection("Test").Get<List<TestItem>>(); // 遍历输出验证 foreach (var item in testItems) { Console.WriteLine($"A: {item.A}, B: {item.B}"); }
方式二:使用GetChildren()遍历
你调用的GetChildren()本身没有错误,但它返回的是IEnumerable<IConfigurationSection>,这是一个延迟执行的Linq迭代器,直接输出它的ToString()结果就会显示你看到的System.Linq.Enumerable+SelectEnumerableIterator2[...]`,这不是错误,只是你没有正确遍历它。正确的用法是:
var testSections = Configuration.GetSection("Test").GetChildren(); foreach (var section in testSections) { // 从子节点中读取属性值 string aValue = section["A"]; string bValue = section["B"]; Console.WriteLine($"A: {aValue}, B: {bValue}"); }
3. 确认Configuration的构建正确
确保你已经正确加载了appsettings.json,完整的Configuration构建代码参考:
var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build();
同时要确认已经安装了Microsoft.Extensions.Configuration.Json NuGet包,否则AddJsonFile方法会找不到。
先修正JSON格式,再按照上面的方式读取,应该就能解决你的问题了。如果还有其他异常,可以把完整的代码和错误栈贴出来,我再帮你排查。
内容的提问来源于stack exchange,提问作者user




