Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e 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; }
}
like image 366
Triplesticks Avatar asked Mar 10 '17 19:03

Triplesticks


People also ask

What is the use of IOptions in .NET Core?

IOptionsMonitor is a Singleton service that retrieves current option values at any time, which is especially useful in singleton dependencies. IOptionsSnapshot is a Scoped service and provides a snapshot of the options at the time the IOptionsSnapshot<T> object is constructed.

How do you inject IConfiguration in NET Core 6?

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } private IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // TODO: Service configuration code here... } public void Configure(IApplicationBuilder app, ...

Can I use app config in .NET Core?

Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.


1 Answers

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.

like image 189
Anderson Pimentel Avatar answered Oct 22 '22 03:10

Anderson Pimentel