The ASP. NET MVC custom Jsonresult class to prevent maxjsonlength from exceeding the limit

Source: Internet
Author: User
Tags httpcontext stack trace

Not long ago, when I was working on a project, I used the MVC Webapi to return a big Data report with a 500 error, as shown in:

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. Review the stack trace for more information about the error and where it is 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. version:2.0.50727.4955

The reason for the error from above is that the object exceeds the default maximum limit when the JavaScriptSerializer is serialized, so we need a class to rewrite the Jsonresult to allow for larger data.

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 being disclosed to third party Web sites when this is US Ed 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} to replace the return Json (data).
Of course you can also control JavaScriptSerializer's Maxjsonlength yourself:

return new Largejsonresult () {Data = output, maxjsonlength = Int. MaxValue};

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

The ASP. NET MVC custom Jsonresult class to prevent maxjsonlength from exceeding the limit

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.