Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
Some Googling led me to realise that there is indeed a limit, and this limit is quite low.
Most of the posts explained how to increase the limit but also explained why this was a bad idea and that you should instead reduce your JSON size.
I agree with this, better to return what you can to the client and tell them to "try again" for whatever is left.
But this poses a problem - how do you know how much data you can return at once?
Google drew a blank on this one.
This little function here will do the trick:
using System.Configuration;
using System.Web.Configuration;
public int GetMaxJSONLength()
{
Configuration cConfig =
WebConfigurationManager.OpenWebConfiguration(null);
return ((ScriptingWebServicesSectionGroup)
cConfig.
SectionGroups["system.web.extensions"].
SectionGroups["scripting"].
SectionGroups["webServices"]
).JsonSerialization.MaxJsonLength;
}
This can be executed from anywhere, it doesn't have to be part of the web project itself.
Something else to be aware of - any strings in your return value will be encoded.
That means characters like < and > will become \u003c and \u003e - 6 times longer than they were previously.
So if you have a string containing html this can make a substantial difference to the length of the string.
To account for this make sure you use the length of the encoded string, not the original.
No comments:
Post a Comment