C# Asp.Net Core从appsettings.json获取json数组
检索appsettings.json中的json数组集时遇到问题 使用Configuration.GetSection(“xxx”).GetChildren()获取json数组时,返回值为null。然后我用下面的方法解决了这个问题,它成功了 appsettings.json中的:C# Asp.Net Core从appsettings.json获取json数组,c#,asp.net-core,C#,Asp.net Core,检索appsettings.json中的json数组集时遇到问题 使用Configuration.GetSection(“xxx”).GetChildren()获取json数组时,返回值为null。然后我用下面的方法解决了这个问题,它成功了 appsettings.json中的: { "EndPointConfiguration": [ { "UserName": "TestUser", "Email": "Test@global.com" },
{
"EndPointConfiguration": [
{
"UserName": "TestUser",
"Email": "Test@global.com"
},
{
"UserName": "TestUser",
"Email": "Test@global.com"
}
]
}
public class EndPointConfiguration
{
public string UserName { get; set; }
public string Email { get; set; }
}
var endPointConfiguration = Configuration.GetSection("EndPointConfiguration").Get<EndPointConfiguration[]>();
然后我创建类:
{
"EndPointConfiguration": [
{
"UserName": "TestUser",
"Email": "Test@global.com"
},
{
"UserName": "TestUser",
"Email": "Test@global.com"
}
]
}
public class EndPointConfiguration
{
public string UserName { get; set; }
public string Email { get; set; }
}
var endPointConfiguration = Configuration.GetSection("EndPointConfiguration").Get<EndPointConfiguration[]>();
最后,使用EndPointConfiguration类的数组将起作用:
{
"EndPointConfiguration": [
{
"UserName": "TestUser",
"Email": "Test@global.com"
},
{
"UserName": "TestUser",
"Email": "Test@global.com"
}
]
}
public class EndPointConfiguration
{
public string UserName { get; set; }
public string Email { get; set; }
}
var endPointConfiguration = Configuration.GetSection("EndPointConfiguration").Get<EndPointConfiguration[]>();
var endPointConfiguration=Configuration.GetSection(“endPointConfiguration”).Get();
我对.net核心相当陌生,不知道为什么配置.GetSection().GetChildren()不能工作。任何精通的人都能帮助给出答案吗?谢谢。使用GetChildren()
方法将返回您的IEnumerable
,如果使用简单类型(如字符串列表),这将非常有用。例如:
{
"EndPointUsernames": [
"TestUser1",
"TestUser2",
"TestUser3",
"TestUser4"
]
}
可以很容易地添加到字符串数组中,而无需定义单独的类,如EndPointConfiguration
。从这里你只需打个电话
string[]userNames=Configuration.GetSection(“EndPointUsernames”).GetChildren().ToArray().Select(c=>c.Value).ToArray();
检索这些值。在您的示例中,您已经正确地将结果强键入到
EndPointConfiguration
对象列表中。getChildren返回IConfigurationSection
的列表,这是一个由键定义并具有值()的节。对象数组不是IConfigurationSection
,因为它不包含要引用的字符串键。非常感谢您的解释!