在使用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 }