【问题标题】:Configuration.GetSection("ConnectionStringName").Get<?> always nullConfiguration.GetSection("ConnectionStringName").Get<?> 始终为空
【发布时间】:2018-12-27 19:29:16
【问题描述】:

在我的 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") 返回“Key”、“Path”和“Value”属性,但它无法进行绑定并在设置中返回 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 输出的即时窗口屏幕截图,我可以在其中看到键、路径和值

从下面的截图可以看出设置变量为空

【问题讨论】:

  • 设置是否来自 appsettings.json 文件?如果是这样,这个文件是配置为“内容”还是“复制到输出目录”?
  • 是的,就是appsetting.json文件,配置为内容
  • appsettings.json的结构是什么?
  • @LearningCurve 向我们展示您的应用设置 json 文件
  • 不在我的电脑上,但它是 ConnectionStrings 部分的基础,其中包含 OdeToFood 连接字符串。别忘了,Configuration.Getsection 可以读取文件并提供值。没有发生的是到 ConnectionsSeting 文件的映射

标签: c# dependency-injection asp.net-core-2.0 class-library asp.net-core-mvc-2.0


【解决方案1】:

我不确定你想用提供的代码实现什么,但为了获得值而不是 null,你应该在 appsettings.json 中有以下部分:

{
  ...

  "ConnectionStrings": {
    "OdeToFood": {
      "Name": "someConncetionString"
    } 
  },

  ...
}

那么下面的代码会返回对象:

var settings = Configuration
    .GetSection("ConnectionStrings:OdeToFood")
    .Get<ConnectionSetings>();

【讨论】:

  • 这正是我现在正在做的@Alex,但设置为空。
  • @LearningCurve,你能分享你的 appsettings.json 吗?
  • 我已经用 appsettings.json 修改了我的问题和错误截图@Alex
  • @LearningCurve 您的 json 数据缺少“名称”
  • 非常感谢亚历克斯。如此愚蠢的错误!我的一天结束了,昨天无法尝试您提出的解决方案。再次感谢@NKosi,感谢他帮助我设置了这个设计。
猜你喜欢
  • 2018-02-11
  • 1970-01-01
  • 2019-11-04
  • 2017-05-12
  • 2014-08-06
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多