Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

In one of my controller actions I am returning a very large JsonResult to fill a grid.

I am getting the following InvalidOperationException exception:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

Setting the maxJsonLength property in the web.config to a higher value unfortunately does not show any effect.

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

I don't want to pass it back as a string as mentioned in this SO answer.

In my research I came across this blog post where writing an own ActionResult (e.g. LargeJsonResult : JsonResult) is recommended to bypass this behaviour.

Is this then the only solution?
Is this a bug in ASP.NET MVC?
Am I missing something?

Any help would be most appreciated.

like image 203
Martin Buberl Avatar asked Sep 26 '22 18:09

Martin Buberl


People also ask

What is the maximum value for MaxJsonLength?

The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.

Can I set an unlimited length for MaxJsonLength?

The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).

What is Jsonserialization MaxJsonLength?

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 JsonSerializer class. The default value is 102400 characters.


1 Answers

It appears this has been fixed in MVC4.

You can do this, which worked well for me:

public ActionResult SomeControllerAction()
{
  var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
  jsonResult.MaxJsonLength = int.MaxValue;
  return jsonResult;
}
like image 262
Orion Edwards Avatar answered Oct 11 '22 13:10

Orion Edwards