0

I'm getting the following exception when returning a large JSON result:

The length of the string exceeds the value set on the maxJsonLength property.

I am trying to catch the exception where the serialisation happens but this does not happen.

            try
            {
                return new JsonResult()
                {
                    Data = LargeJsonData,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            catch (Exception)
            {
                return "Error";
            }

I do NOT want the adjust the property. I just want to catch the exception and handle appropriately.

I have found the following question which seems like a duplicate, but the accepted answer modifies the maxJsonLength property.

How to catch error during serialization or deserialization using the JSON JavaScriptSerializer

Thanks, Steve

Community
  • 1
  • 1
Stephen A
  • 3
  • 1
  • Possible duplicate. Please, read this article. http://stackoverflow.com/questions/1151987/can-i-set-an-unlimited-length-for-maxjsonlength-in-web-config – Yeldar Kurmangaliyev Jun 02 '15 at 10:53
  • May be you are not able to catch it because the error is thrown after control returns from the method. Try checking the `Length` of the data manually and comparing it to the `maxJsonLength` property. – Nikhil Girraj Jun 02 '15 at 10:57
  • Look here http://stackoverflow.com/a/19235980/2115584 – Baximilian Jun 02 '15 at 11:04

1 Answers1

1

This will be being thrown when the ExecuteContext method is called on the Json result. You could work around this by defining your own override for JsonResult and catching it here, e.g.

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        try
        {
            base.ExecuteResult(context);
        }
        catch(Exception ex)
        {
            //Handle it
        }
    }

And then returning an instance of this instead of the JsonResult.

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30