Can I set an unlimited length for maxJsonLength in web.config?

If you are using MVC 4, be sure to check out this answer as well.


If you are still receiving the error:

  • after setting the maxJsonLength property to its maximum value in web.config
  • and you know that your data's length is less than this value
  • and you are not utilizing a web service method for the JavaScript serialization

your problem is is likely that:

The value of the MaxJsonLength property applies only to the internal JavaScriptSerializer instance that is used by the asynchronous communication layer to invoke Web services methods. (MSDN: ScriptingJsonSerializationSection.MaxJsonLength Property)

Basically, the "internal" JavaScriptSerializer respects the value of maxJsonLength when called from a web method; direct use of a JavaScriptSerializer (or use via an MVC action-method/Controller) does not respect the maxJsonLength property, at least not from the systemWebExtensions.scripting.webServices.jsonSerialization section of web.config. In particular, the Controller.Json() method does not respect the configuration setting!

As a workaround, you can do the following within your Controller (or anywhere really):

var serializer = new JavaScriptSerializer();

// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;

var resultData = new { Value = "foo", Text = "var" };
var result = new ContentResult{
    Content = serializer.Serialize(resultData),
    ContentType = "application/json"
};
return result;

This answer is my interpretation of this asp.net forum answer.


NOTE: this answer applies only to Web services, if you are returning JSON from a Controller method, make sure you read this SO answer below as well: https://stackoverflow.com/a/7207539/1246870


The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).

You can set the MaxJsonLength property on your web.config:

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