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

Exception

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

Explanation


The JsonResult in ASP.NET MVC has a MaxJsonLength property, which represents the maximum length of data possible in a JSON response. Exceeding the default value of this property will throw the above exception.

Solution


Using the code below, we want to return the base64 string of a JPG file via JSON.

public JsonResult Test()
{
    string base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(Server.MapPath("~/Images/test.jpg")));

    return Json(base64);
}

The base64 length of the JPG file used in this example exceeds the default value of the MaxJsonLength property throwing the above exception. In order to handle this exception, you have to override the default JsonResult

public JsonResult Test()
{
    string base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(Server.MapPath("~/Images/test.jpg")));

    return new JsonResult
    {
        Data = base64,
        MaxJsonLength = int.MaxValue // set the maximum length of data
    };
}