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

ASP.NET嵌套数组属性ModelBinder绑定失效,StepId始终为空

问题原因与解决方案

核心问题

[ModelBinder(Name = "id")]属性仅作用于模型绑定流程(比如表单提交、URL查询参数、路由参数的绑定),而你的场景是JSON格式的请求体,JSON的反序列化流程并不识别这个属性,所以无法将JSON里的id字段映射到StepId属性上,导致StepId始终为空Guid。

解决方案

根据你使用的JSON序列化库,选择对应的属性来指定JSON字段名:

1. 使用.NET自带的System.Text.Json(.NET Core 3.0+ 默认)

给StepId加上[JsonPropertyName("id")]属性:

public class StepRequest {
    [JsonPropertyName("id")]
    public Guid StepId { get; set; }

    public bool? Visible { get; set; }
}

2. 使用Newtonsoft.Json(Json.NET)

如果项目中配置了使用Newtonsoft.Json作为JSON序列化器,就用[JsonProperty("id")]属性:

public class StepRequest {
    [JsonProperty("id")]
    public Guid StepId { get; set; }

    public bool? Visible { get; set; }
}

额外说明

如果你的API同时需要支持表单提交和JSON请求,可以同时保留两个属性,兼顾两种绑定场景:

public class StepRequest {
    [ModelBinder(Name = "id")]
    [JsonPropertyName("id")]
    public Guid StepId { get; set; }

    public bool? Visible { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:39:07