无法从 asp dot net 3.1 中的 appsettings.json 读取字符串数组

Posted

技术标签:

【中文标题】无法从 asp dot net 3.1 中的 appsettings.json 读取字符串数组【英文标题】:Imposible to read array of strings form appsettings.json in asp dot net 3.1 【发布时间】: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 我明白了,似乎人们正在这样做,但使用了扩展库。感谢您指出。 【参考方案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>>();

【讨论】:

以上是关于无法从 asp dot net 3.1 中的 appsettings.json 读取字符串数组的主要内容,如果未能解决你的问题,请参考以下文章

如何从 ASP.NET Core 3.1 中的存储库类创建确认电子邮件回调

使用自包含框架时,dot net core 3.1 的设置 CI 构建配置失败

没有从 select2 ajax 调用 Asp dot net Web 方法

无法使用 Chrome 登录 Dot Net Core 3 ASP.Net App,但可以使用 Firefox

如何从剃刀视图提交具有动态列表的模型中的列表? ASP.NET 核心 3.1

如何从 Asp.NET Core 3.1 启动类访问 launchSettings.json 中的 `applicationUrl` 属性?