字符串的长度超过maxJsonLength属性上设置的值(WebMethod)

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

背景

我在 ASPX 页面的代码隐藏中有一个 WebMethod:

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

我正在使用 jQuery 向它发送 AJAX 请求:

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

这通常可以正常工作。

问题

WebMethodreturns大约88KB的数据时,框架returns一个500 Internal Server Error的HTTP请求。 HTTP 响应正文包含一堆 JSON 格式的 .NET 异常信息。反序列化后,响应包含以下信息:

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)

疑难解答

我通过更改 Web.config 中名为 maxJsonlength 的属性解决了这个问题:

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

来自 .