You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置数组值绑定类实例失败:获取值始终为null求排查

问题排查与修复方案

1. 错误的配置绑定方法

你使用的GetValue<Rootobject>("Serilog")仅适用于获取单个简单类型值(如string、int),无法绑定包含数组、嵌套类的复杂对象。正确的绑定方式是使用GetSection结合Get<T>方法:

// 方式1:直接绑定Serilog类型(配置根节点为Serilog)
var serilogConfig = builder.Configuration.GetSection("Serilog").Get<Serilog>();

// 方式2:保留Rootobject结构,直接绑定整个配置(无需指定路径)
var x = builder.Configuration.Get<Rootobject>();

2. 类型不匹配导致绑定失败

Args类中rollingInterval定义为bool类型,但配置里对应的是字符串值"Day",类型转换失败会导致整个对象绑定失败。需修改类型为string或对应枚举:

修改为string类型:

public class Args
{          
    public string path { get; set; }          
    public string formatter { get; set; }
    public string restrictedToMinimumLevel { get; set; }          
    // 改为string匹配配置中的"Day"
    public string rollingInterval { get; set; }
}

或者使用枚举(更规范):

public enum RollingInterval
{
    Day,
    Hour
    // 按需添加其他枚举值
}

public class Args
{          
    public string path { get; set; }          
    public string formatter { get; set; }
    public string restrictedToMinimumLevel { get; set; }          
    public RollingInterval rollingInterval { get; set; }
}

3. 路径字符串未转义

内存字典中的"c:\log.json"存在转义字符问题,\l会被视为无效转义序列,导致路径值异常。需改为:

{ "Serilog:WriteTo:1:Args:path", @"c:\log.json" },
// 或者
{ "Serilog:WriteTo:1:Args:path", "c:\\log.json" },

修复后的完整示例

修正后的内存集合:

var data = new Dictionary<string, string>
{
    { "Serilog:WriteTo:0:Args:restrictedToMinimumLevel", "Error" },
    { "Serilog:WriteTo:0:Name", "Console" },
    { "Serilog:WriteTo:1:Args:formatter", "Serilog.Formatting.Json.JsonFormatter" },
    { "Serilog:WriteTo:1:Args:path", @"c:\log.json" },
    { "Serilog:WriteTo:1:Args:restrictedToMinimumLevel", "Verbose" },
    { "Serilog:WriteTo:1:Args:rollingInterval", "Day" },
    { "Serilog:WriteTo:1:Name", "File" },
};

修正后的绑定代码:

builder.Configuration.AddInMemoryCollection(data);
var serilogConfig = builder.Configuration.GetSection("Serilog").Get<Serilog>();

完成以上修改后,配置即可正确绑定到类对象,不会再返回null。

内容的提问来源于stack exchange,提问作者user14267126

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:01:19