ASP.NET MVC 返回JsonResult序列化内容超出最大限制报错的解决办法

在使用MVC的时候我们经常会在Controller的Action方法中返回JsonResult对象,但是有时候你如果序列化的对象太大会导致JsonResult从Controller的Action返回后抛出异常,显示Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. 

比如

1 ublic ActionResult SomeControllerAction()
2 {
3   var veryLargeCollection=GetCollection();//由于GetCollection方法返回了一个庞大的C#对象集合veryLargeCollection,导致下面在veryLargeCollection被封装到JsonResult对象,然后被Action方法返回后,MVC做Json序列化时报错
4   return Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
5 
6 }

解决的办法就是在返回JsonResult之前设置其MaxJsonLength属性为Int32的最大值即可,当然如果这样都还是太大了,你只有想办法拆分你要返回的对象分多次返回给前端了。。。

1 public ActionResult SomeControllerAction()
2 {
3   var veryLargeCollection=GetCollection();
4   var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
5   jsonResult.MaxJsonLength = int.MaxValue;
6   return jsonResult;
7 }
原文地址:https://www.cnblogs.com/OpenCoder/p/5333491.html