System.Text.Json序列化大列表时JSON被截断的问题求助
解决System.Text.Json序列化大对象列表被截断的问题
1. 优先使用框架内置JSON格式化器,避免手动序列化
不要手动调用JsonSerializer.Serialize后返回Ok(string),直接返回对象让ASP.NET(Core/Framework)内置格式化器处理序列化,框架会自动处理响应输出逻辑,减少截断风险:
return Ok(result);
同时配置System.Text.Json的驼峰命名规则:
ASP.NET Core 配置方式
在Program.cs(或Startup.cs)中添加JSON选项配置:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // 可选:根据需求添加其他配置,比如忽略空值、处理循环引用 // options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; // options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; });
ASP.NET Framework 配置方式
在Global.asax.cs的Application_Start方法中替换默认JSON格式化器:
var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.JsonFormatter); formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter { SerializerSettings = new JsonSerializerSettings { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } });
2. 调整响应输出大小限制
ASP.NET Core 配置
- 配置Kestrel服务器的响应缓冲限制:
builder.WebHost.ConfigureKestrel(serverOptions => { serverOptions.Limits.MaxResponseBufferSize = null; // 无限制,或设置具体值如1024*1024*100(100MB) serverOptions.Limits.MaxRequestBufferSize = null; });
- 部署在IIS时,补充
web.config配置:
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="104857600" /> <!-- 100MB --> </requestFiltering> </security> </system.webServer>
ASP.NET Framework 配置
除已有配置外,补充以下web.config节点:
<system.web> <httpRuntime maxRequestLength="104857" executionTimeout="3600" /> <!-- 100MB,超时3600秒 --> </system.web> <system.webServer> <serverRuntime uploadReadAheadSize="104857600" /> <!-- 100MB --> </system.webServer>
3. 手动序列化时的输出优化(若必须手动序列化)
如果一定要手动生成JSON字符串,使用ContentResult确保完整输出:
var jsonString = JsonSerializer.Serialize(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return new ContentResult { Content = jsonString, ContentType = "application/json", StatusCode = 200 };
同时保持WriteIndented为false(默认值),减少输出体积,降低截断概率。
4. 检查自定义中间件/过滤器的截断逻辑
排查项目中的自定义中间件、Action过滤器(如日志、压缩组件),确认是否存在响应大小限制配置,调整对应参数取消不必要的截断。
内容的提问来源于stack exchange,提问作者Evert Dausy
相关产品推荐
相关产品推荐

