7

I have the following settings:

{
  "AppSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "Database": "local",
    "ValidOrigins": [ "http://localhost:61229" ]
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

I do the binding:

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

I have the following settings file:


    public class AppSettings
    {
        public string ConnectionString = "";
        public string Database = "";

        public List<string> ValidOrigins { get; set; }
    }

Doing the binding:

    AppSettings settings = new AppSettings();
    Configuration.GetSection("AppSettings").Bind(settings);

settings.ValidOrigins is OK, but ConnectionString and Database are both null. What am I doing wrong?

Henk Mollema
  • 40,690
  • 11
  • 89
  • 103
gyozo kudor
  • 6,286
  • 10
  • 49
  • 77

3 Answers3

13

The binder will only bind properties and not fields. Try using properties instead of fields for ConnectionString and Database.

public string ConnectionString { get; set; }

public string Database { get; set; }
Henk Mollema
  • 40,690
  • 11
  • 89
  • 103
1

Also make sure that your properties aren't defined as auto-properties by accident:

// ❌ WRONG

public class Configuration {
   public string Database { get; }
}


// ✅ CORRECT

public class Configuration {
   public string Database { get; set; }    // <----- Property must have a public setter
}
silkfire
  • 22,873
  • 14
  • 77
  • 98
0

As 'Henk' said, you need to use properties instead of fields. I run your code on my machine except that corrected properties issue. It works with following class structure:

public class AppSettings
{
    public string ConnectionString { get; set; }
    public string Database { get; set; }
    public List<string> ValidOrigins { get; set; }
}
Afshar Mohebi
  • 9,219
  • 13
  • 76
  • 122