【发布时间】:2020-10-19 16:07:06
【问题描述】:
我正在尝试从 appsettings.json 中读取一些对象。 json 包含这个结构:
...
"DevicePool": [
{ "device":"185.215.0.91:9082", "phonePair":["644004268", "644049008"],"enabled": "true" },
{ "device":"185.215.0.92:9083", "phonePair":["644491698", "644935005"],"enabled": "true" }
]
...
我试着这样读:
public DevicePoolMgr(IConfiguration configuration, string devicePoolConfigKey)
{
_devices = new List<DevicePoolItem>();
_configuration = configuration;
string adbPath = Startup.AppConfig["AppConstants:AdbPath"];
var valuesSection = _configuration.GetSection(devicePoolConfigKey);
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
bool enabled = section.GetValue<bool>("enabled");
if (!enabled) continue;
string device = section.GetValue<string>("device");
var phoneNumbers = section.GetValue<string[]>("phonePair");
DevicePhonePair phonePair = new DevicePhonePair(phoneNumbers[0], phoneNumbers[1]);
_devices.Add(new DevicePoolItem() {Device = device, PhonePair = phonePair, Enabled = enabled});
}
}
这很有效。我无法获得 phonePair 部分。设备获取它的值,也启用但 phonePair 为空。我见过其他人使用这种方式从 appsettings 中读取字符串列表。所以,不知道是什么原因。
【问题讨论】:
-
你需要做和
"DevicePool"一样的事情:见this answer -
我明白了,似乎人们正在这样做,但使用了扩展库。感谢您指出。
标签: c# asp.net .net asp.net-core appsettings