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

使用ConfigurationBuilder与appsettings.json如何实现属性名与JSON键不同的绑定?

解决配置绑定中属性名与JSON键不匹配的问题

.NET配置系统的对象绑定逻辑,和System.Text.Json的序列化逻辑是独立的两套机制,所以[JsonPropertyName]特性不会被配置绑定器识别,这就是你遇到问题的原因。

正确的解决方案:使用[ConfigurationKeyName]特性

配置绑定器专门提供了[ConfigurationKeyName]特性来指定属性对应的配置键名,它位于Microsoft.Extensions.Configuration.Binder命名空间下。

示例代码:

using Microsoft.Extensions.Configuration.Binder;

public class ProcessSettings
{
    public const string SectionName = "ProcessSettings";

    // 对应JSON中的"captureTrace"键
    [ConfigurationKeyName("captureTrace")]
    public bool CaptureTrace { get; set; }

    // 嵌套类场景示例
    [ConfigurationKeyName("nestedPropertyGroup")]
    public NestedGroupSettings NestedGroup { get; set; }
}

public class NestedGroupSettings
{
    [ConfigurationKeyName("innerConfigKey")]
    public string InnerConfigValue { get; set; }
}

绑定代码无需额外修改

你的绑定逻辑保持原有写法即可,配置绑定器会自动识别[ConfigurationKeyName]的映射:

var procSettings = builder.GetSection(ProcessSettings.SectionName).Get<ProcessSettings>();

关于BinderOptions的说明

你提到的BinderOptions.BindNonPublicProperties仅用于控制是否绑定类的非公共属性,和键名映射逻辑无关,注意区分使用场景。

内容的提问来源于stack exchange,提问作者T.S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 11:02:16