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?
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; }
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With