简体   繁体   中英

asp.net core ioptions with a list

I'm trying to read a list of values from the appsettings.json file. I'm able to read the Logging values with no problem, but the list values (ie Servers ) are null:

appsettings.json:

{
 "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
           "Default": "Debug",
           "System": "Information",
           "Microsoft": "Information"
      }
 },
 "Servers": [
      "SCHVW2K12R2-DB",
      "SCHVW2K12R2-DB\\MSSQL2016",
      "SCHVW2K8R2-DB"
    ]
}

Object Classes:

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; }
}

Try deleting the Servers class and changing AppSettingsConfiguration to:

public class AppSettingsConfiguration
{
    public Logging Logging { get; set; }
    public string[] Servers { get; set; }
}

Servers is a simple string array, not a complex type.

To use your original classes, you can change your json to this. IMO, this is more readable.

{
     "Logging": {
          "IncludeScopes": false,
          "LogLevel": {
               "Default": "Debug",
               "System": "Information",
               "Microsoft": "Information"
          }
     },
     "Servers": {
        "Names": [
          "SCHVW2K12R2-DB",
          "SCHVW2K12R2-DB\\MSSQL2016",
          "SCHVW2K8R2-DB"
        ]
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM