c# - Configuration.GetSection("ConnectionStringName").Get始终为空
问题描述
在我的 Asp.net Core 2.0 应用程序中,我试图按照@Nkosi here的建议实现在我的类库项目中不使用 IConfiguration 构造函数依赖项的连接字符串的设计。
在这种方法中,它无法将配置实例绑定到类型的新实例,如下面的代码行所示
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,你应该在 appsettings.json 中有以下部分:
{
...
"ConnectionStrings": {
"OdeToFood": {
"Name": "someConncetionString"
}
},
...
}
然后以下代码将返回该对象:
var settings = Configuration
.GetSection("ConnectionStrings:OdeToFood")
.Get<ConnectionSetings>();
推荐阅读
- java - 使用 $in Mongodb - Java 进行不区分大小写的搜索
- hp-uft - UFT OTA - 获取复制的测试集文件夹的 ID
- java - 如何为 try & catch 实现指数延迟/睡眠
- css - 如何独立于其他列或行关注一列
- python - 来自 setup.py 的 dh_python2 版本化依赖项
- javascript - 从firebase数据库获取数据不起作用
- node.js - 使用 KMS、Node 从 S3 解密 SES 消息
- ios - 在启动屏幕中禁用智能反转
- tkinter - 在谷歌云平台中使用 tkinter 时出现错误消息
- python - CUDA/pycuda - 在带有参数向量的经典函数上实现 GPU“映射”函数