【问题标题】:Imposible to read array of strings form appsettings.json in asp dot net 3.1无法从 asp dot net 3.1 中的 appsettings.json 读取字符串数组
【发布时间】: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


【解决方案1】:

这对你有用吗?我创建了一个类来序列化,如果我们知道模型数据

public class DevicePool
{
    public string device { get; set; }
    public List<string> phonePair { get; set; } = new List<string>();
    public bool enabled { get; set; }
}

然后像下面这样阅读

var devicePools= _configuration.GetSection("DevicePool").Get<List<DevicePool>>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2020-06-11
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2017-08-09
    相关资源
    最近更新 更多