我正在使用jQuery的自动完成功能。当我试图检索超过17000条记录的列表(每个记录不会超过10个字符长度)时,它超过了长度并抛出错误:

异常信息: 异常类型:InvalidOperationException 异常消息:使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过maxJsonLength属性设置的值。

我可以在web.config中设置maxJsonLength的无限长度吗?如果不是,我可以设置的最大长度是多少?


当前回答

如果你正在使用MVC 4,一定要看看这个答案。


如果你仍然收到错误:

在web.config中将maxJsonLength属性设置为最大值之后 你知道你的数据长度小于这个值 并且您没有使用web服务方法进行JavaScript序列化

你的问题可能是:

MaxJsonLength属性的值仅应用于异步通信层用于调用Web服务方法的内部JavaScriptSerializer实例。(MSDN: ScriptingJsonSerializationSection。MaxJsonLength属性)

基本上,当从web方法调用时,“内部”JavaScriptSerializer尊重maxJsonLength的值;直接使用JavaScriptSerializer(或通过MVC action-method/Controller使用)不尊重maxJsonLength属性,至少不尊重web.config的systemwebextension .scripting. webservices . jsonserialization部分。特别是,Controller.Json()方法不尊重配置设置!

作为一种变通方法,你可以在你的控制器(或任何地方)中执行以下操作:

var serializer = new JavaScriptSerializer();

// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;

var resultData = new { Value = "foo", Text = "var" };
var result = new ContentResult{
    Content = serializer.Serialize(resultData),
    ContentType = "application/json"
};
return result;

这个答案是我对这个asp.net论坛答案的解释。

其他回答

我解决了添加以下代码的问题:

String confString = HttpContext.Current.Request.ApplicationPath.ToString();
Configuration conf = WebConfigurationManager.OpenWebConfiguration(confString);
ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
section.MaxJsonLength = 6553600;
conf.Save();
 JsonResult result = Json(r);
 result.MaxJsonLength = Int32.MaxValue;
 result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
 return result;

我在ASP中遇到了这个问题。NET Web表单。它完全忽略了网络。配置文件设置,所以我这样做:

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        serializer.MaxJsonLength = Int32.MaxValue; 

        return serializer.Serialize(response);

当然,总的来说,这是一种糟糕的做法。如果您要在web服务调用中发送这么多数据,您应该考虑另一种方法。

如果你仍然得到错误后,web。配置设置如下:

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

    

我是这样解决的:

   public ActionResult/JsonResult getData()
   {
      var jsonResult = Json(superlargedata, JsonRequestBehavior.AllowGet);
      jsonResult.MaxJsonLength = int.MaxValue;
      return jsonResult;
    }

我希望这能有所帮助。

你可以像其他人说的那样在配置中设置它,或者你可以在序列化器的单个实例中设置它,比如:

var js = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };