Working around JavaScriptSerializer’s maximum output length limit in ASP.NET MVC applications

Posted: (EET/GMT+2)

 

If you are working with large sets of data and try to return that data back to the client using .NET's built-in JavaScriptSerializer class, you might run into the following error:

<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="52428800"/>
      </webServices>
    </scripting>
  </system.web.extensions>

In ASP.NET MVC applications, this serializer is also used when you call the "return Json(…)" method inside your controller to conveniently send JSON data back to the client.

While today running into this issue, I noticed that most search engine (I usually use Bing) hits lead to telling that you should edit your web.config file and increase the MaxJsonLength property to a larger value, such as 52428800. (The default value for the web.config settings is 2097152 characters, that is, 4 MiB worth of Unicode string data.)

However, when calling the JavaScriptSerializer directly or using the Json property, this setting in web.config has no effect. Instead, you must directly set the MaxJsonLength property of the serializer when working with it. Here's an example from inside an MVC controller action method:

var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 10 * 1024 * 1024; // 10 MiB characters

var data = new { SomeProperty = "SomeValue", SomeOtherProperty = 12345 };
ContentResult result = new ContentResult{
    Content = serializer.Serialize(resultData),
    ContentType = "application/json"
};
return result;

Hope this helps!