首页 > 解决方案 > 配置 GetSection 返回对象部分的空值

问题描述

您好,我在 a 中使用 aajson配置文件.NET Core App,但我不明白为什么我会为作为对象的子部分获得 null 值:

{
    "tt": {
        "aa":3,
        "x":4
    },
    "Url":333,
    "Config": {
        "Production": {
            "RedisAddress": {
                "Hostname": "redis0",
                "Port": 6379
            },
            "OwnAddress": {
                "Hostname": "0.0.0.0",
                "Port": 9300
            }
        },
        "Dev": {
            "RedisAddress": {
                "Hostname": "redis0",
                "Port": 6379
            },
            "OwnAddress": {
                "Hostname": "0.0.0.0",
                "Port": 9300
            },
            "Logger": "logger.txt"
        }
    }
}

当我尝试GetSection("Config")GetSection("tt")获得值null时,它会返回原始类型的值,例如我的情况Url

有趣的是,如果我在里面偷看,configuration.Providers[0].Data我会看到图片中的所有内容:

在此处输入图像描述

为什么它为object类型返回 null?

代码

WebHostBuilder builder = new WebHostBuilder();
builder.UseStartup<Startup>();

string appPath = AppDomain.CurrentDomain.BaseDirectory;
string jsonPath = Path.Combine(Directory.GetParent(Directory.GetParent(appPath).FullName).FullName, "appsettings.json");

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(appPath)
    .AddJsonFile(jsonPath, optional: true, reloadOnChange: true)
    .Build();

var sect = configuration.GetSection("Config");//has value null
var sect2 = configuration.GetSection("tt");//has value null
var sect3 = configuration.GetSection("Url"); has value 333

标签: c#asp.net-core

解决方案


你的例子没有错。Value您所指的属性是 a string,它null适用于您的sectsect2变量,仅仅是因为它们都不包含string值 - 正如您所说,它们都是对象。

如果你想从 eg 中提取一个值sect2,你可以使用这样的方法:

var aaValue = sect2.GetValue<int>("aa");

还有更多选项可以获取这样的部分的值。这是另一个绑定到 POCO 的示例:

public class TT
{
    public int AA { get; set; }
    public int X { get; set; }
}

var ttSection = sect2.Get<TT>();

如果您只想获得一个嵌套值,那么根本没有理由使用GetSection。例如,您可以执行以下操作:

var redisHostname = configuration["Config:Dev:RedisAddress:Hostname"];

推荐阅读