asp.net mvc自定义JsonResult类来防止MaxJsonLength超过限制

前不久在做一个项目的时候,我用到了mvc的webapi返回了一个大数据,结果报了500错误,如下图所示:

Server Error in ‘/’ Application.


Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.]
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +551497
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +74
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +6
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +341
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +10
   System.Web.Mvc.<>c__DisplayClass14.<InvokeActionResultWithFilters>b__11() +20
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +251
   System.Web.Mvc.<>c__DisplayClass16.<InvokeActionResultWithFilters>b__13() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +178
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314
   System.Web.Mvc.Controller.ExecuteCore() +105
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +34
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +59
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8682542
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4955

从上面可以看出错误的原因是对象在JavaScriptSerializer序列化的时候超过了默认的最大限制,所以我们需要一个类来重写JsonResult从而允许更大的数据。

using System;
using System.Web.Script.Serialization;

namespace System.Web.Mvc
{
    public class LargeJsonResult : JsonResult
    {
        const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
        public LargeJsonResult()
        {
            MaxJsonLength = 1024000;
            RecursionLimit = 100;
        }

        public int MaxJsonLength { get; set; }
        public int RecursionLimit { get; set; }

        public override void ExecuteResult( ControllerContext context )
        {
            if( context == null )
            {
                throw new ArgumentNullException( "context" );
            }
            if( JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals( context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase ) )
            {
                throw new InvalidOperationException( JsonRequest_GetNotAllowed );
            }

            HttpResponseBase response = context.HttpContext.Response;

            if( !String.IsNullOrEmpty( ContentType ) )
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if( ContentEncoding != null )
            {
                response.ContentEncoding = ContentEncoding;
            }
            if( Data != null )
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
                response.Write( serializer.Serialize( Data ) );
            }
        }
    }
}

  你可以在Action里面使用return new LargeJsonResult(){ Data = data }  来替代 return Json(data).
当然你也可以自己控制JavaScriptSerializer的MaxJsonLength:

return new LargeJsonResult() { Data = output, MaxJsonLength = int.MaxValue };

转载自:https://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/

时间: 2024-08-27 13:20:53

asp.net mvc自定义JsonResult类来防止MaxJsonLength超过限制的相关文章

ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)

前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和解密>http://www.cnblogs.com/insus/p/5983645.html那今次Insus.NET在ASP.NET MVC实现自定义验证Authorize Attribute. 实现之前,Insus.NET对usp_Users_VeryLoginVerify修改一下,改为更好理解与使用

asp.net mvc 自定义pager封装与优化

asp.net mvc 自定义pager封装与优化 Intro 之前做了一个通用的分页组件,但是有些不足,从翻页事件和分页样式都融合在后台代码中,到翻页事件可以自定义,再到翻页和样式都和代码分离, 自定义分页 pager 越来越容易扩展了. HtmlHelper Pager扩展 Pager V1.0 : 1 /// <summary> 2 /// Pager V1.0 3 /// </summary> 4 /// <param name="helper"&

[转]ASP.NET MVC的帮助类HtmlHelper和UrlHelper

本文转自:http://www.cnblogs.com/greatandforever/archive/2010/04/20/1715914.html?login=1 在ASP.NET MVC框架中没有了自己的控件,页面显示完全就回到了写html代码的年代.还好在asp.net mvc框架中也有自带的HtmlHelper和UrlHelper两个帮助类.另外在MvcContrib扩展项目中也有扩展一些帮助类,这样我们就不光只能使用完整的html来编写了需要显示的页面了,就可以使用这些帮助类来完成,

ASP.NET MVC之JsonResult(六)

前言 这一节我们利用上节所讲Unobtrusive Ajax并利用MVC中的JsonResult来返回Json数据. JsonResult 上节我们利用分部视图返回数据并进行填充,当我们发出请求需要获取数据时都是返回json,所以我们在上一节的基础上进一步学习. 既然是返回Json数据,我们接下来要在控制器上进行定义如下代码: (1)通过选择的类别名称来筛选数据 private IEnumerable<Blog> GetBlog(string selectedCategory) { var d

ASP.net MVC自定义错误处理页面的方法

在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那么默认的,当这个Action抛出了异常时MVC将会显示Error视图,该视图位于~/Views/Shared目录下. 设置HandleError属性 可以通过设置下面这些属性来更改HandleErrorAttribute特性的默认处理: ExceptionType.指定过滤器处理那种或哪些类型的异常

ASP.NET MVC自定义验证Authorize Attribute

前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和解密>http://www.cnblogs.com/insus/p/5983645.html那今次Insus.NET在ASP.NET MVC实现自定义验证Authorize Attribute. 实现之前,Insus.NET对usp_Users_VeryLoginVerify修改一下,改为更好理解与使用

ASP.NET MVC 创建控制器类过程

MvcHandler.ProcessRequestInit()方法: 1.1获取控制器的名称string requiredString = this.RequestContext.RouteData.GetRequiredString("controller"); 1.2创建控制器类工厂  返回IControllerFactory类型 默认创建的工厂实例为DefaultControllerFactory factory = this.ControllerBuilder.GetContr

Asp.net mvc自定义Filter简单使用

自定义Filter的基本思路是继承基类ActionFilterAttribute,并根据实际需要重写OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted这四个中的一个或多个方法. 注意类名一定要以Attribute结尾. 故名思义,Action执行前,执行后,结果返回前,结果返回后.所以它们的执行先后顺序就是OnActionExecuting,OnActionExecuted,Action,OnResultEx

ASP.NET MVC 路由系统类

RouteData public class RouteData { private RouteValueDictionary _dataTokens; private IRouteHandler _routeHandler; private RouteValueDictionary _values; public RouteData() { this._values = new RouteValueDictionary(); this._dataTokens = new RouteValueD