Search code examples
asp.netjsonwebformswebmethod

The length of the string exceeds the value set on the maxJsonLength property (WebMethod)


Background

I have a WebMethod in the code-behind for an ASPX page:

[WebMethod]
public static string GetServiceDetail()
{
    //...
}

I'm using jQuery to send an AJAX request to it:

$.ajax({
    type: "POST",
    url: url + "GetServiceDetail",
    data: JSON.stringify({}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
})

This generally works correctly.

Problem

When the WebMethod returns about 88KB of data, the framework returns a 500 Internal Server Error to the HTTP request. The HTTP response body contains a bunch of .NET exception information in JSON format. When deserialised, the response has this information:

System.InvalidOperationException:

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

   at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat)
   at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat)
   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)

Troubleshooting

  • I'm not using JavaScriptSerializer in the WebMethod at all. As the stack trace shows, the exception is happening outside of my code.
  • Existing StackOverflow questions seem to be about explicit JSON serialisation or different technologies. They imply changing the Web.config value doesn't work.

Solution

  • I solved this by changing an attribute called maxJsonlength in Web.config:

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

    Sourced from https://stackoverflow.com/a/1151993/238753.