带有列表的asp.net核心ioptions

Tri*_*cks 8 c# json asp.net-core

我正在尝试从appsettings.json文件中读取值列表.我能够Logging毫无问题地读取值,但列表值(即Servers)为空:

appsettings.json:

{
 "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
           "Default": "Debug",
           "System": "Information",
           "Microsoft": "Information"
      }
 },
 "Servers": [
      "SCHVW2K12R2-DB",
      "SCHVW2K12R2-DB\\MSSQL2016",
      "SCHVW2K8R2-DB"
    ]
}
Run Code Online (Sandbox Code Playgroud)

对象类:

public class AppSettingsConfiguration
{
    public Logging Logging { get; set; }
    public Servers Servers { get; set; }
}

//Logging Objects
public class Logging
{
    public bool IncludeScopes { get; set; }
    public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
    public string Default { get; set; }
    public string System { get; set; }
    public string Microsoft { get; set; }
}

//Server Objects
public class Servers
{
    public List<string> Names { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

And*_*tel 5

尝试删除Servers该类并更改AppSettingsConfiguration为:

public class AppSettingsConfiguration
{
    public Logging Logging { get; set; }
    public string[] Servers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Servers 是一个简单的字符串数组,而不是复杂的类型。

  • 别客气!请查看http://stackoverflow.com/help/someone-answers (3认同)

小智 5

要使用原始类,您可以将 json 更改为此。IMO,这更具可读性。

{
     "Logging": {
          "IncludeScopes": false,
          "LogLevel": {
               "Default": "Debug",
               "System": "Information",
               "Microsoft": "Information"
          }
     },
     "Servers": {
        "Names": [
          "SCHVW2K12R2-DB",
          "SCHVW2K12R2-DB\\MSSQL2016",
          "SCHVW2K8R2-DB"
        ]
     }
}
Run Code Online (Sandbox Code Playgroud)