[英]configuration.getValue or configuration.getsection always returns null
[英]Configuration.GetSection(“ConnectionStringName”).Get<?> always null
在我的Asp.net核2.0应用程序,我想实现的不是设计用来连接字符串为IConfiguration构造函数依赖于我的类库项目由@Nkosi建议在这里 。
在这种方法中,无法将配置实例绑定到type的新实例,如以下代码行所示
public void ConfigureServices(IServiceCollection services) {
//...
var settings = Configuration
.GetSection("ConnectionStrings:OdeToFood")
.Get<ConnectionSetings>();
//...verify settings (if needed)
services.AddSingleton(settings);
}
public class ConnectionSetings
{
public string Name { get; set; }
}
我可以看到Configuration.GetSection("ConnectionStrings:OdeToFood")
返回“键”,“路径”和“值”属性,但是它无法进行绑定,并且在设置中返回null。
我曾在ppl推荐如下解决方案时遇到过类似的问题,但没有一个对我有用。
services.Configure<ConnectionsSetings>(Configuration.GetSection("ConnectionStrings:OdeToFood"));
也,
Configuration
.GetSection("ConnectionStrings:OdeToFood").Bind<>
以下是appsettings.json
{
"Greeting": "Hello!!!",
"ConnectionStrings": {
"OdeToFood": "Server=(localdb)\\MSSQLLocalDB;Database=OdeToFood;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
以下是Configuration.GetSection输出的即时窗口屏幕快照,在其中我可以看到键,路径和值
从下面的屏幕截图中可以看出,设置变量为null
我不确定要使用提供的代码实现什么,但是为了获取值而不是null,您应该在appsettings.json中包含以下部分:
{
...
"ConnectionStrings": {
"OdeToFood": {
"Name": "someConncetionString"
}
},
...
}
然后以下代码将返回该对象:
var settings = Configuration
.GetSection("ConnectionStrings:OdeToFood")
.Get<ConnectionSetings>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.