Configuration.GetSection 总是返回 Value 属性 null [英] Configuration.GetSection always returns Value property null

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

问题描述

每次调用Configuration.GetSection时,返回对象的Value属性总是为null.

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

我的Startup构造函数

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

    this.Configuration = builder.Build();
}

我的ConfigureServices方法

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

    services.AddOptions();

    services.AddMvc();
}

我的appsettings.json

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

我用来定义 SqliteSettings 的类

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
}

我在想 JSON 可能需要具有相同数量的属性才能匹配,或者它可能与数据类型定义有关,但也许这些完全无关.

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.

推荐答案

根据 微软文档:

当 GetSection 返回匹配的部分时,不会填充 Value.一种当section存在时返回Key和Path.

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

如果您想查看该部分的值,您需要调用 GetChildren() 方法:Configuration.GetSection("SqliteSettings").GetChildren();

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

或者你可以使用:Configuration.GetSection(SqliteSettings").Get().JSON 不需要具有相同数量的属性来匹配.不匹配的可为空属性将被设置为空,不可为空的不匹配属性将被设置为其默认值(例如 int 将设置为 0).

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).

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆