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

ASP.NET Core GET请求序列化复杂对象时嵌套集合绑定失败如何解决?

问题根因与解决方案

1. 首先修正DTO定义

ASP.NET Core 默认模型绑定器仅绑定公共可读写属性,不会绑定公共字段,同时要保证属性名和序列化参数名完全对齐:

public class CompletedAuditDto
{
    public int UserId { get; set; }
    public string CategoryId { get; set; }
    public long StartMillis { get; set; }
    public long EndMillis { get; set; }
    public string GroupByAttributeTypeId { get; set; }
    // 字段改属性,和JSON参数名对齐
    public IEnumerable<TypeAttributeDto> SelectedAttributes { get; set; }
}

public class TypeAttributeDto
{
    // 字段改属性
    public int TypeId { get; set; }
    // 属性名和JSON里的AttributeIds对齐,不要用AttrIds
    public IEnumerable<int> AttributeIds { get; set; }
}

2. 调整qs序列化配置

ASP.NET Core 对于嵌套集合的查询字符串绑定,要求显式指定索引,不能使用无索引的[]格式,需要配置qs序列化参数:

// 前端序列化代码示例
const queryParams = qs.stringify(payload, {
  arrayFormat: 'indices', // 生成带数字索引的数组格式
  allowDots: true // 用点表示嵌套属性,而非方括号
})

生成的合法查询字符串格式如下:

UserId=1&CategoryId=39&StartMillis=1609459200000&EndMillis=1635724799000&GroupByAttributeTypeId=105&SelectedAttributes[0].TypeId=100&SelectedAttributes[0].AttributeIds[0]=1&SelectedAttributes[1].TypeId=105&SelectedAttributes[1].AttributeIds[0]=6697

补充说明

如果参数复杂度较高导致URL长度超出浏览器/服务器限制,可按需调整ASP.NET Core的查询字符串长度上限:

// Program.cs 配置示例
builder.Services.Configure<HttpOptions>(opt => 
{
    // 按需调整最大查询字符串大小,单位为字节
    opt.MaxQueryStringSize = 2 * 1024 * 1024; 
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:15:04