您的位置:首页 > 编程语言 > ASP

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

2016-03-29 16:37 615 查看
在使用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.

比如

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

}


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

public ActionResult SomeControllerAction()
{
var veryLargeCollection=GetCollection();
var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: