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
  • 44,194
  • 12
  • 93
  • 104
gyozo kudor
  • 6,284
  • 10
  • 53
  • 80

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
  • 44,194
  • 12
  • 93
  • 104
3

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
  • 24,585
  • 15
  • 82
  • 105
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
  • 10,479
  • 17
  • 82
  • 126