简体   繁体   中英

Configuration.GetValue<T> returning null but Bind works

I'm having a problem getting data from my appsettings.json . The file looks like:

  "Integrations": {
    "System01": {
      "Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
      "User": "admin",
      "Password": "admin"
    },
    "System02": {
      "Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
      "User": "admin",
      "Password": "admin"
    },
  }

I have the following DTO:

public class IntegrationsConfigurationDto
{
    public string Host { get; set; }
    public string User { get; set; }
    public string Password { get; set; }
}

When trying to read it like:

var config = _configuration.GetValue<IntegrationsConfigurationDto>("Integrations:System01");

I get null . But if I do:

var config = new IntegrationsConfigurationDto();
_config.Bind("Integrations:System01", config);

I get the values correctly in my config variable.

Why does that happen? How can I use GetValue<T> in this scenario?

Thanks in advance.

GetValue only works for simple values, such as string , int , etc - it doesn't traverse the hierarchy of nested configuration.

Reference: Configuration in ASP.NET Core: GetValue

ConfigurationBinder.GetValue<T> extracts a value from configuration with a specified key and converts it to the specified type. An overload permits you to provide a default value if the key isn't found.

Instead of using Bind , use the following to avoid having to create your own instance of IntegrationsConfigurationDto :

var config = _configuration.GetSection("Integrations:System01")
    .Get<IntegrationsConfigurationDto>();

Reference: Configuration in ASP.NET Core: Bind to an object graph

ConfigurationBinder.Get<T> binds and returns the specified type. Get<T> is more convenient than using Bind .

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