我有以下设置:
{
"AppSettings": {
"ConnectionString": "mongodb://localhost:27017",
"Database": "local",
"ValidOrigins": [ "http://localhost:61229" ]
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
我做绑定:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
我有以下设置文件:
public class AppSettings
{
public string ConnectionString = "";
public string Database = "";
public List<string> ValidOrigins { get; set; }
}
进行绑定:
AppSettings settings = new AppSettings();
Configuration.GetSection("AppSettings").Bind(settings);
settings.ValidOrigins
没问题,但ConnectionString
和Database
都是null
。我做错了什么?
答案 0 :(得分:8)
绑定器只绑定属性而不绑定字段。尝试使用属性而不是ConnectionString
和Database
的字段。
public string ConnectionString { get; set; }
public string Database { get; set; }
答案 1 :(得分:0)
正如'Henk'所说,你需要使用属性而不是字段。我在我的机器上运行你的代码,除了纠正的属性问题。它适用于以下类结构:
public class AppSettings
{
public string ConnectionString { get; set; }
public string Database { get; set; }
public List<string> ValidOrigins { get; set; }
}
答案 2 :(得分:0)
还要确保您的属性未被意外地定义为自动属性:
// ❌ WRONG
public class Configuration {
public string Database { get; }
}
// ✅ CORRECT
public class Configuration {
public string Database { get; set; } // <----- Property must have a public setter
}