ASP.NET返回含重复Base64串的JsonResult时触发无调试异常500错误
故障根因
- 控制器代码存在双重序列化逻辑错误:先通过Newtonsoft.Json将
List<AnnotationModel>序列化为JSON字符串,再传入MVC原生Json()方法做二次序列化,导致响应内容被额外转义,长度显著增加。 - Mvc原生
JsonResult默认使用JavaScriptSerializer序列化,内置最大JSON长度限制为2097152字符(约2MB)。二次序列化后的内容长度一旦超过该阈值,会直接抛出异常。 - 异常触发时机在Action方法执行完成后的MVC管道结果执行阶段,因此单步调试Action代码时无法捕获到异常栈。
- 当列表中存在两份重复的长Base64
DocumentBody时,序列化后的总长度刚好突破2MB阈值,触发报错;移除重复项或使用短字段组合时长度在阈值内,接口即可正常返回。
解决方案
方案1:修正序列化逻辑,取消手动序列化
直接将模型列表传入JsonResult,同时手动配置MaxJsonLength适配大体积响应:
public ActionResult GetAnnotationsForEntity(EntityType entityType, string entityId) { List<AnnotationModel> annotationsForEntity = new List<AnnotationModel>(); if (!string.IsNullOrWhiteSpace(entityId)) { DynamicsHelper.GetAnnotationsForEntity(entityType, new Guid(entityId))?.ToList()?.ForEach(a => { annotationsForEntity.Add(new AnnotationModel(a.Id, GetOffsetDateTimeForTimeZone(a.ModifiedOn), a.FileName, a.Subject, a.DocumentBody, a.NoteText, GetCulture())); }); } return new JsonResult { Data = annotationsForEntity, JsonRequestBehavior = JsonRequestBehavior.AllowGet, // 可根据业务需求调整为合适的最大长度,此处设为100MB MaxJsonLength = 104857600 }; }
方案2:保留Newtonsoft序列化,绕过MVC JsonResult限制
如果需要使用Newtonsoft的序列化配置(如日期格式、命名规则等),则不要使用MVC原生Json()方法,直接返回带JSON头的文本内容,避免二次序列化和长度限制:
public ActionResult GetAnnotationsForEntity(EntityType entityType, string entityId) { List<AnnotationModel> annotationsForEntity = new List<AnnotationModel>(); if (!string.IsNullOrWhiteSpace(entityId)) { DynamicsHelper.GetAnnotationsForEntity(entityType, new Guid(entityId))?.ToList()?.ForEach(a => { annotationsForEntity.Add(new AnnotationModel(a.Id, GetOffsetDateTimeForTimeZone(a.ModifiedOn), a.FileName, a.Subject, a.DocumentBody, a.NoteText, GetCulture())); }); } // 可根据需求配置Newtonsoft的序列化参数 string serializedAnnotations = JsonConvert.SerializeObject(annotationsForEntity); return Content(serializedAnnotations, "application/json"); }
方案3:大体积文件的优化建议
Base64编码会将文件体积增大33%,直接放在列表接口中返回会大幅增加网络开销。可拆分接口设计:列表接口仅返回文件的唯一标识,前端需要展示图片时再单独调用文件获取接口拉取Base64内容,从根源上减小列表接口的响应体积,避免长度限制问题。
内容的提问来源于stack exchange,提问作者drobbinso
相关产品推荐
相关产品推荐

