MVC中JSON字符长度超出限制
MVC中JSON字符长度超出限制ASP.NET MVC中通过JsonResult返回JSON字符串时,当JSON字符串长度过长时,会报如下错误
异常详细信息: System.InvalidOperationException: 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。
由于原来MVC框架内置的JsonResult代码中,在使用JavaScriptSerializer时,都是采用的默认值,没有从maxJsonLength读取值,即忽略了这个配置,所以通过修改 web.config ,设置 jsonSerialization节点maxJsonLength属性值是无效的
解决方法
1、新建一个控制器扩展类
namespace WEBMVC.Helpers { public static class ControllerExtensions { public static int MaxJsonLength{get;set;} public static ControllerExtensions() { MaxJsonLength = 2147483644; } public static System.Web.Mvc.JsonResult LargeJson(this System.Web.Mvc.Controller controlador, object data) { return new System.Web.Mvc.JsonResult() { Data = data, MaxJsonLength = MaxJsonLength, }; } public static System.Web.Mvc.JsonResult LargeJson(this System.Web.Mvc.Controller controlador, object data, System.Web.Mvc.JsonRequestBehavior behavior) { return new System.Web.Mvc.JsonResult() { Data = data, JsonRequestBehavior = behavior, MaxJsonLength = MaxJsonLength }; } //TODO: You can add more overloads, the controller class has 6 overloads } }
2、在需要返回大数据的控制器里面如下调用
using WEBMVC.Helpers;
namespace WEBMVC.Controllers
{
public class VentasController : Controller
{
ControllerExtensions.MaxJsonLength = 1073741824;//1GB,如果需要单独设置长度,如果不需要,则不设置该值
public ActionResult VentasList (){
//Todo: All the action code
return ControllerExtensions.LargeJson(myData);
}
}
}