[英]Configuration binding doesn't work
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
. settings.ValidOrigins
,但ConnectionString
和Database
都是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
.尝试使用属性而不是
ConnectionString
和Database
的字段。
public string ConnectionString { get; set; }
public string Database { get; set; }
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; }
}
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.