Skip to content

MVC3 Unable To Return Large JSON Even with Web Config Patch, Using LargeJsonResult Instead

Updated: at 09:35 PM

I’m trying to download a base64 encoded image that is about 4 Megabytes embedded inside a JSON object.  When I first tried this from my MVC3 Web application, I got the error:

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

I then tried to set the web.config property that everyone seems to reference on the web as follows:

<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization maxJsonLength="2147483645" recursionLimit="100">
            </jsonSerialization>
        </webServices>
        </scripting>
</system.web.extensions>

However, I kept getting the same error over and over.  So, I used the technique suggested in this article

http://thoughtfulcode.wordpress.com/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/

by Brian Reiter to create an override of the JsonResult class.  That actually worked for me, however unfortunately, it does not show the shape of the data that is currently being returned by MVC3.  That is, MVC3 currently returns a JsonResult as follows:

return Json(new
{
    total = blobs.Count,
    data = blobs.ToList()
}, JsonRequestBehavior.AllowGet);
Brian suggest in his article to return his LargeJsonResult, do the following:
return new LargeJsonResult() { Data = output, MaxJsonLength = int.MaxValue };
This does not quite work for what I want.  For my result to work, I needed to modify the result a little and return it as follows:
return
   new LargeJsonResult
       {
           MaxJsonLength = 20000000,
           JsonRequestBehavior = JsonRequestBehavior.AllowGet,
           Data = new
                      {
                          total = blobs.Count,
                          data = blobs.ToList()
                      }
       };
Not much different, but does solve my problem.
Thanks Brian for the nice contribution!