Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

configuration.GetValue list returns null

Tags:

c#

.net

.net-core

I am trying to read a list from appsettings.json file using the GetValue<T> method:

var builder = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

IConfigurationRoot configuration = builder.Build();
var rr = configuration.GetValue<IList<ConnectionSettings>>("Connections");


public class ConnectionSettings
{
    public string Name { get; set; }

    public string Host { get; set; }

    public string Account { get; set; }

    public string Password { get; set; }
}

and my appsettings.json

{
"Connections": [
    {
      "Name": "",
      "Host": "192.168.1.5",
      "Account": "74687",
      "Password": "asdsdadsq"
    },
    {
      "Name": "",
      "Host": "127.0.0.1",
      "Account": "45654",
      "Password": "asdasads"
    }
  ]
}

Problem is that I always get null and I dont understand why.

like image 615
pantonis Avatar asked Dec 15 '17 12:12

pantonis


2 Answers

I have spotted the following issue on GitHub: GetValue<T> not working with lists

Long story short: It is by design.

So you can try this:

var result = new List<ConnectionSettings>();
var rr = configuration.GetSection("Connections").Bind(result);
like image 93
Athanasios Kataras Avatar answered Oct 29 '22 14:10

Athanasios Kataras


According to the documentation for GetValue<>, it gets the value of a (single) key and converts it to the specified type. Unfortunately, it doesn't throw an error if the value can't be converted, which is the situation you're running into.

I believe that Get<> would be preferable in your situation.

var rr = configuration.GetSection("Connections").Get<IList<ConnectionSettings>>();

According to Get<>'s documentation, it:

Attempts to bind the configuration instance to a new instance of type T. If this configuration section has a value, that will be used. Otherwise binding by matching property names against configuration keys recursively.

This allows you to get the value directly or, if it can't find the property, it looks for nested objects that contain a matching property.

An alternative would be as @AthanasiosKataras says; use Bind<>. This is helpful when you might have a sparse configuration in which you want to overlay some values with either default or calculated values.

like image 31
Matt DeKrey Avatar answered Oct 29 '22 16:10

Matt DeKrey