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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM