Configuration.GetSection("ConnectionStringName").Get<?> 始终为空

Configuration.GetSection("ConnectionStringName").Get<?> always null

在我的 Asp.net Core 2.0 应用程序中,我正在尝试按照@Nkosi .

在这种方法中,无法将配置实例绑定到类型的新实例,如以下代码行所示

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") returning "Key"、"Path" 和 "Value" 属性,但它无法执行绑定和 return 在设置中为空。

我见过类似的问题,其中有人推荐了如下解决方案,但其中 none 对我有用。

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 输出的直接 window 屏幕截图,我可以在其中看到键、路径和值

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

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

{
  ...

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

  ...
}

然后下面的代码将return对象:

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