GetSection始终返回null

GetSection始终返回null

本文介绍了Configuration.GetSection始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次调用 Configuration.GetSection 时,返回对象的 Value 属性始终为空。



我的启动构造函数

  public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile( appsettings.json,可选) :false,reloadOnChange:true)
.AddEnvironmentVariables();

this.Configuration = builder.Build();
}

我的 ConfigureServices 方法

  public void ConfigureServices(IServiceCollection服务)
{
services.Configure< SqliteSettings>(opts => ; Configuration.GetSection( SqliteSettings)。Bind(opts));

services.AddOptions();

services.AddMvc();
}

我的 appsettings.json

  {
SqliteSettings:{
DataSource: C:\\ db.sqlite,
NewDatabase:是,
版本:3
}
}

我用来定义SqliteSettings的类

 公共类SqliteSettings 
{
公共字符串DataSource {获取;组; }

公共布尔? NewDatabase {get;组; }

public int?版本{get;组; }

公用字符串密码{get;组; }

公有长? CacheSize {get;组; }

//更多属性
}

我在想JSON可能需要具有相同数量的属性以进行匹配,或者它可能与数据类型定义有关,但是也许它们是完全不相关的。

解决方案

只需修改您的 ConfigureServices 方法,如下所示:

  public void ConfigureServices(IServiceCollection服务)
{
services.AddOptions();

services.Configure< SqliteSettings>(Configuration.GetSection( SqliteSettings));;

services.AddMvc();
}

,它应该可以工作。


Every time I call Configuration.GetSection, the Value property of the returned object is always null.

My Startup constructor

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

    this.Configuration = builder.Build();
}

My ConfigureServices method

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<SqliteSettings>(opts => Configuration.GetSection("SqliteSettings").Bind(opts));

    services.AddOptions();

    services.AddMvc();
}

My appsettings.json

{
  "SqliteSettings": {
    "DataSource": "C:\\db.sqlite",
    "NewDatabase": true,
    "Version": 3
  }
}

The class I'm using to define SqliteSettings

public class SqliteSettings
{
    public string DataSource { get; set; }

    public bool? NewDatabase { get; set; }

    public int? Version { get; set; }

    public string Password { get; set; }

    public long? CacheSize { get; set; }

    // More properties
}

I was thinking the JSON might need to have the same amount of properties to match, or is it might be something to do with data type definitions, but maybe those are completely unrelated.

解决方案

Just modify your ConfigureServices method to be like following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();

    services.Configure<SqliteSettings>(Configuration.GetSection("SqliteSettings"));

    services.AddMvc();
}

and it should work.

这篇关于Configuration.GetSection始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:20