Frank Wang's inspirations on .NET

IEnumerable<Inspiration> inspirations = from i in DataContext.Inspirations where i.Sharable == true select i

How to configure maxJsonLength in ASP.NET AJAX applications

Tuesday, August 5, 2008 5:10 PM

Invoking web methods from client scripts is fun. But before you roll out your cool applications into the production, please don't forget to reconfigure the max JSON string length, represented by either the maxJsonLength value in the web configuration file or the MaxJsonLength property of the JavaScriptSerializer class.

The maximum length of JSON strings, by default is 2097152 characters, which is equivalent to 4 MB of Unicode string data. This should be good enough for most of the web applications. If the size of serialized data you want to send to the client is larger than this default value, you may change it either programmatically or declaratively (in the web.config file of the web site). However, I personally wouldn't go over the 4MB threshold because serializing a large chunk of data across the wire normally causes huge performance penalty. From my experience, you may want to take a serious look at your application design if you need JSON strings longer than 2097152 characters.

To set this value in your code, you can simply assign an integer to the JavaScriptSerializer.MaxJsonLength property. Alternatively, you can configure the max length in the system.web.extensions configuration section in web.config. The example below sets the maxJswonLength value to 500000 characters. Also bear in mind that the maxJsonLength in the web.config file automatically overrides the JavaScriptSerializer.MaxJsonLength property.

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



Feedback

# re: How to configure maxJsonLength in ASP.NET AJAX applications

I have .Net Framework 3.5 and I saw that the maximum length of JSON strings, by default is 102400 characters,not 2097152 characters as written in your article.
Moreover, I'd like to add more detailed explanation how to set programmatically MaxJsonLength property in web.config:
string str = HttpContext.Current.Request.ApplicationPath.ToString();
Configuration conf = WebConfigurationManager.OpenWebConfiguration(str);
ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
section.MaxJsonLength = 5000000;
conf.Save();
3/13/2009 6:08 AM | julia

# re: How to configure maxJsonLength in ASP.NET AJAX applications

Thank you very much! That solved my problem. 7/27/2011 3:25 PM | Jara

# re: How to configure maxJsonLength in ASP.NET AJAX applications

Thank you very much MAN!
You save my time)) 7/28/2011 9:55 AM | Irakli

Post a comment