Tuesday, March 17, 2015

Handling larger JSON string value in MVC and avoiding exceptions

Working with JSON 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.

We can convert a massive collection of complex objects into a simple string and passed across and then completely regenerated in its original collection .
However sometimes these strings can get big and I mean really big, like exceeding default values. and when this happens, exceptions happen.

In this post I will explain how you can prevent it in MVC .
You can simply add the MaxJsonLength property to a specific value depending on the context of your specific action :
JsonResult jResult = Json(users, JsonRequestBehavior.AllowGet);
jResult.MaxJsonLength = int.MaxValue;
return jResult;
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 
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
    };
}