February 16, 2021 06:49 by
Peter
Working with JSON within Web Services recently has become the latest and greatest simply because it plays so nicely with others and can often be very easily serialized and deserialized to fit your needs.
There is just something rewarding about having a massive collection of complex objects that can be thrown into a simple string and passed across however you see fit and then completely regenerated in its original collection in just a handful of code.
However sometimes these strings can get big and I mean really big, like exceeding default values big, and when this happens, exceptions happen. This post will cover a few ways that you can prevent a nasty InvalidOperationException that may look something like this with ease:
The Problem
You decide that paging data is for losers and decide to pull a graph of all of the data within your database, which will hypothetically contain thousands of complex objects, each with additional properties of their own. If your dataset is large enough, you’ll find yourself quickly exceeding the bounds that your Serializer can handle and you’ll be met with an exception and no data.
The Solution
There are three basic methods of handling this depending on your current environment:
Setting the MaxJsonLength property default value within your web.config. (This will only apply to web-services that handle JSON).
Setting the MaxJsonLength property of a JavascriptSerializer object to perform your serialization.
If you are using MVC4 to handle returning your JSON values, you may want to override the default JsonResult() ActionResult and change the maximum size manually.
Either of these changes will help you avoid any bumps in the road when passing across your large JSON values.
Option I: The MaxJsonLength Property for handling JSON in Web Services
The MaxJsonLength property which can be set within the web.config of your application controls the maximum size of the JSON strings that are accepted by the JsonSerializerclass. The default value is 102400 characters.
In order to increase the size of this value – you can just add the following code to your web.config file and set it to the value that you desire:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<!-- Update this value to change the value to
a larger value that can accommodate your JSON
strings -->
<jsonSerialization maxJsonLength="86753090" />
</webServices>
</scripting>
</system.web.extensions>
</configuration>
It is important to know that this setting within the web.config will only apply to actual Web Services that handle your JSON strings using the internal JsonSerializer. If you are still encountering issues after applying this change, you will likely want to continue reading and consider using an instance of the JsonSerializer class to handle setting this value.
Option II: Using the JavaScriptSerialzier and the MaxJsonLength Property to Handle Serializing JSON Values
Using an instance of a JavascriptSerializer will not actually inherit the previously defined within the web.config (as the web.config only applies to Web Services that handle the JSON) so you can easily just create an instance of the serializer and set the property accordingly:
// Creates an instance of your JavaScriptSerializer
// and Setting the MaxJsonLength
var serializer = new JavaScriptSerializer() { MaxJsonLength = 86753090 };
// Perform your serialization
serializer.Serialize("Your JSON Contents");
This will allow you to easily your larger data and adjust your maximum size easily.
Option III: Overriding the MVC4 JsonResult Action Result to Handle the Maximum Size
Much like the previous examples, every time that you are going to return a JsonResultyou can simply add the MaxJsonLength property to a specific value depending on the context of your specific action:
return new JsonResult() {
Data = "Your Data",
MaxJsonLength = 86753090
};
Or using the Json() method:
JsonResult result = Json("Your Data");
result.MaxJsonLength = 8675309;
However, if you want a more widespread solution that you could use within a single area of your application, you may want to consider overriding the JsonResult class and set your value within this newer class:
// This ActionResult will override the existing JsonResult
// and will automatically set the maximum JSON length
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue // Use this value to set your maximum size for all of your Requests
};
}
From a JSON to a JMAN
Those are just a few methods that you should be able to use if you ever encounter an issue when passing larger JSON strings across your Controllers or through the use of Web Services. I am sure that there are likely several other ways to handle these same problems, but hopefully one of these will help you out if you are in a tight spot.
HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.