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

.NET 6 Web API读取JSON配置数组时字段为空问题

解决.NET 6 Web API读取JSON配置时属性值为空的问题

出现这个问题的核心原因有两个,直接修改对应代码即可解决:

1. 类型不匹配 + 私有Setter限制

JSON配置里的SourceAppId和TargetAppId是数值类型,但你定义的类属性是string,同时属性的set访问器是private——配置绑定系统无法给私有Setter赋值,也无法自动把数值转成字符串(除非额外配置转换规则)。

修改后的类定义

internal class ProductMigration
{
    public class ProductMigrationItem
    {
        // 类型改为int匹配JSON数值,同时把Setter改成public
        public int SourceAppId { get; set; }
        public int TargetAppId { get; set; }
    }

    public ProductMigrationItem Product { get; set; }
}

如果业务上确实需要把ID存为字符串,要么把JSON里的数值改成带引号的字符串:

{
  "ProductsMigration": {
    "Products": [
        {
            "Product": 
            {
            "SourceAppId": "4215",
            "TargetAppId": "6218"
            }
        }
    ]
  }
}

然后保持类里的string类型,同时把Setter改成public:

public string SourceAppId { get; set; }
public string TargetAppId { get; set; }

2. 验证读取代码

你的读取逻辑本身没问题,确保_Configuration是通过依赖注入正确获取的IConfiguration实例即可:

var items = _Configuration.GetSection("ProductsMigration:Products").Get<ProductMigration[]>();

修改后重新运行,SourceAppId和TargetAppId就能正确读取到配置值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:33:13