Fix maxJsonLength error in ASP.NET MVC 4 applications

Are you running into the following error in a ASP.NET Framework 4.x MVC project, and have already tried changing the max response values in web.config?

Error:

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

Solution:

If you are using the Json() return method in your MVC controller, then the solution below will most likely fix the problem for you. The default Json() return method implementation has a MaxJsonLength limit defined which does not always respect the value set in web.config. In order to change the MaxJsonLength we can override the Json() method ourselves with the following code. Add this code to your MVC controller:

        /// <summary>
        /// Overrides the default Json() method to remove the limit on MaxJsonLength. This is essential for handling larger AJAX JSON responses successfully.
        /// In scenarios where the number of records returned increases significantly (e.g., from 100 to 500 or 1000), the default Json() method's length limit can lead to failures. 
        /// This override addresses that issue by setting the MaxJsonLength to the maximum possible integer value, effectively making it unlimited.
        /// </summary>
        /// <param name="data">The data to serialize.</param>
        /// <param name="contentType">The content type of the response.</param>
        /// <param name="contentEncoding">The content encoding of the response.</param>
        /// <param name="behavior">The JSON request behavior.</param>
        /// <returns>A JsonResult object with an unlimited MaxJsonLength.</returns>
        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonResult()
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior,
                MaxJsonLength = Int32.MaxValue
            };
        }

Afterwards, rebuild your project and try again to see if the error is fixed now.

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *