Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

c# - Configuration.GetSection always returns null

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the Microsoft Docs:

When GetSection returns a matching section, Value isn't populated. A Key and Path are returned when the section exists.

If you want to see the values of that section you will need to call the GetChildren() method: Configuration.GetSection("SqliteSettings").GetChildren();

Or you can use: Configuration.GetSection("SqliteSettings").Get<SqliteSettings>(). The JSON does not need to have the same amount of properties to match. Unmatched nullable properties will be set to null and non-nullable unmatched properties will be set to their default value (e.g. int will be set to 0).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...