【问题标题】:Can I set an unlimited length for maxJsonLength in web.config?我可以在 web.config 中为 maxJsonLength 设置无限长度吗?
【发布时间】:2010-11-12 05:25:42
【问题描述】:

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

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

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

【问题讨论】:

  • 有些事情可能很明显,所以如果您已经考虑过,请原谅; Json 字符串还包括每条记录周围的大括号、每个字段名称 [和值] 周围的引号,以及字段名称和值。因此,将字段名称设置为单个字符并确保如果该值不是字符串,那么您可以正确设置字段类型,使其不包含引号。

标签: asp.net asp.net-mvc json


【解决方案1】:

我使用它,它适用于剑道网格读取请求。

{ 
  //something
   var result = XResult.ToList().ToDataSourceResult(request);
   var rs = Json(result, JsonRequestBehavior.AllowGet);
   rs.MaxJsonLength = int.MaxValue;
   return rs;
}

【讨论】:

    【解决方案2】:

    如果您使用的是 MVC 4,请务必同时查看 this answer


    如果您仍然收到错误:

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

    您的问题很可能是:

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

    基本上,“内部”JavaScriptSerializer 在从 Web 方法调用时尊重 maxJsonLength 的值;直接使用 JavaScriptSerializer(或通过 MVC 操作方法/控制器使用)确实尊重 maxJsonLength 属性,至少不来自 web.config 的 systemWebExtensions.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;
    

    这个答案是我对this asp.net forum answer的解读。

    【讨论】:

    • 你的回答真的很有帮助,因为我在 asp.net mvc 中使用Json() 操作结果方法。
    • 是的,我也是一个 Json() 受苦的人。谢谢!
    • 虽然它是完全正确的并且值得拥有它的位置,但这是值得一读的问题之一 :)。谢谢!
    • 如果您使用的是 MVC4,请参阅@fanisch 的回答。
    • 反序列化怎么样?我在操作的模型绑定中遇到了这个错误。
    【解决方案3】:

    修复 ASP.NET MVC:如果您只想修复导致问题的特定操作,请更改此代码:

    public JsonResult GetBigJson()
    {
        var someBigObject = GetBigObject();
        return Json(someBigObject);
    }
    

    到这里:

    public JsonResult GetBigJson()
    {
        var someBigObject = GetBigObject();
        return new JsonResult()
        {
            Data = someBigObject,
            JsonRequestBehavior = JsonRequestBehavior.DenyGet,
            MaxJsonLength = int.MaxValue
        };
    }
    

    功能应该相同,您可以返回更大的 JSON 作为响应。


    基于ASP.NET MVC源码的解释:可以查看Controller.Json方法在ASP.NET MVCsource code中做了什么

    protected internal JsonResult Json(object data)
    {
        return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
    }
    

    它正在调用其他Controller.Json方法:

    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
    

    通过contentTypecontentEncoding 的对象是null。所以基本上在控制器中调用return Json(object)就相当于调用return new JsonResult { Data = object, JsonRequestBehavior = sonRequestBehavior.DenyGet }。您可以使用第二种形式并参数化JsonResult

    那么当您设置MaxJsonLength 属性(默认为空)时会发生什么? 这是passed downJavaScriptSerializer.MaxJsonLength 属性,然后JavaScriptSerializer.Serialize 方法是called

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    if (MaxJsonLength.HasValue)
    {
        serializer.MaxJsonLength = MaxJsonLength.Value;
    }
    
    if (RecursionLimit.HasValue)
    {
        serializer.RecursionLimit = RecursionLimit.Value;
    }
    
    response.Write(serializer.Serialize(Data));
    

    当你不设置序列化程序的MaxJsonLenght 属性时,它是takes default value,只有2MB。

    【讨论】:

    • 谢谢!第一个选项节省一些时间=D
    【解决方案4】:

    注意:此答案仅适用于 Web 服务,如果您从 Controller 方法返回 JSON,请确保您也阅读了以下 SO 答案:https://stackoverflow.com/a/7207539/1246870


    MaxJsonLength 属性不能无限,是一个整数属性,默认为 102400 (100k)。

    您可以在 web.config 中设置 MaxJsonLength 属性:

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

    【讨论】:

    • 它是一个整数,所以你可以设置的最大值是:2147483644
    • @despart:你的意思是 2 147 483 647。
    • @kmcc049,IMO 的值没有错,因为如果您查看问题,OP 没有问“maxJsonLength 的默认值是多少?” (顺便说一句,投票第二多的答案是回答这个错误的问题),他试图将此属性设置为“无限”,但由于是整数,因此 maximum 可能的值是2147483647 as @ depsart 和@Descár 指出。
    • 很好,但如果您在使用 MVC 的 return Json() 或其他东西时遇到此问题,请注意以下 @David Murdoch 的回答
    • @Dercsár:有什么意义? 2147483644 是能被 1024 整除的最大整数。
    【解决方案5】:

    我遵循了vestigal的回答并得到了这个解决方案:

    当我需要将大型 json 发布到控制器中的操作时,我会得到著名的“使用 JSON JavaScriptSerializer 进行反序列化时出错。字符串的长度超过了 maxJsonLength 属性上设置的值。\r\n参数名称:输入值提供者”。

    我所做的是新建一个ValueProviderFactory,LargeJsonValueProviderFactory,并在GetDeserializedObject方法中设置MaxJsonLength = Int32.MaxValue

    public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
    {
    private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
    {
        IDictionary<string, object> dictionary = value as IDictionary<string, object>;
        if (dictionary != null)
        {
            foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
                LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
        }
        else
        {
            IList list = value as IList;
            if (list != null)
            {
                for (int index = 0; index < list.Count; ++index)
                    LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
            }
            else
                backingStore.Add(prefix, value);
        }
    }
    
    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return (object) null;
        string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
        if (string.IsNullOrEmpty(end))
            return (object) null;
    
        var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};
    
        return serializer.DeserializeObject(end);
    }
    
    /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
    /// <returns>A JSON value-provider object for the specified controller context.</returns>
    /// <param name="controllerContext">The controller context.</param>
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");
        object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
        if (deserializedObject == null)
            return (IValueProvider) null;
        Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
        LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
        return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
    }
    
    private static string MakeArrayKey(string prefix, int index)
    {
        return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
    }
    
    private static string MakePropertyKey(string prefix, string propertyName)
    {
        if (!string.IsNullOrEmpty(prefix))
            return prefix + "." + propertyName;
        return propertyName;
    }
    
    private class EntryLimitedDictionary
    {
        private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
        private readonly IDictionary<string, object> _innerDictionary;
        private int _itemCount;
    
        public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
        {
            this._innerDictionary = innerDictionary;
        }
    
        public void Add(string key, object value)
        {
            if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
                throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
            this._innerDictionary.Add(key, value);
        }
    
        private static int GetMaximumDepth()
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            if (appSettings != null)
            {
                string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
                int result;
                if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
                    return result;
            }
            return 1000;
         }
      }
    }
    

    然后,在 Global.asax.cs 的 Application_Start 方法中,将 ValueProviderFactory 替换为新的:

    protected void Application_Start()
    {
        ...
    
        //Add LargeJsonValueProviderFactory
        ValueProviderFactory jsonFactory = null;
        foreach (var factory in ValueProviderFactories.Factories)
        {
            if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
            {
                jsonFactory = factory;
                break;
            }
        }
    
        if (jsonFactory != null)
        {
            ValueProviderFactories.Factories.Remove(jsonFactory);
        }
    
        var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
        ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
    }
    

    【讨论】:

    • 我尽我所能,只有你的回答拯救了我的一天,这应该被接受的答案
    • 使用此代码,我们能够覆盖 4 mb 的 MVC 控制器最大 json 反序列化限制,但是有没有办法覆盖 web-api 控制器最大 json 反序列化限制
    【解决方案6】:

    如果在 web.config 设置后仍然出现错误,如下所示:

    <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;
        }
    

    我希望这会有所帮助。

    【讨论】:

    • 在 web.config 中设置 maxJsonLength 是不必要的,设置 jsonResult.MaxJsonLength 就足够了(至少它对我有用(MVC5))
    • 这很有帮助,谢谢。
    • 哇它的工作谢谢。
    【解决方案7】:
     JsonResult result = Json(r);
     result.MaxJsonLength = Int32.MaxValue;
     result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
     return result;
    

    【讨论】:

      【解决方案8】:

      问题真的是你是否真的需要返回 17k 条记录?您打算如何处理浏览器中的所有数据?无论如何,用户不会滚动浏览 17000 行。

      更好的方法是仅检索“前几个”记录并根据需要加载更多记录。

      【讨论】:

      • 来自 json 的默认列表将提供 17k 条记录。但自动完成功能将仅列出与用户键入的字符匹配的记录,因此不需要更多滚动列表。所以我需要为 maxJsonLength 设置无限长度,它可以序列化 17k 数据。
      • 您可以结合使用服务器端和客户端过滤。在客户端过滤所有数据可能很困难,更不用说网络延迟了。
      • 不久前遇到了同样的问题,我选择为自动完成实现一个“onsearch”处理程序,并让 Web 服务调用传递“搜索”文本并使用搜索条件作为过滤器。这意味着更多单独的 ajax 请求,即在页面加载时获得完整列表,但这也意味着所有请求/响应都大大小了。
      【解决方案9】:

      在 MVC 4 中你可以这样做:

      protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
      {
          return new JsonResult()
          {
              Data = data,
              ContentType = contentType,
              ContentEncoding = contentEncoding,
              JsonRequestBehavior = behavior,
              MaxJsonLength = Int32.MaxValue
          };
      }
      

      在您的控制器中。

      加法:

      对于您需要指定的参数感到困惑的任何人,调用可能如下所示:

      Json(
          new {
              field1 = true,
              field2 = "value"
              },
          "application/json",
          Encoding.UTF8,
          JsonRequestBehavior.AllowGet
      );
      

      【讨论】:

      • 我可以确认上面的方法在 MVC 4 中很有效,谢谢 fanisch。
      • 我也可以确认。将此代码放在基本控制器中绝对是最简洁的方法。
      • 这也可以通过将“MaxJsonLength = Int32.MaxValue”添加到单个操作结果中来实现。如果更改不是控制器或项目范围内所需的。
      • 这是最好的答案。 MaxJsonLength 可以为每个控制器配置。
      • 警告:此解决方案禁用响应的压缩(如果请求)。在您的操作中添加此过滤器:stackoverflow.com/questions/3802107/…
      【解决方案10】:

      替代 ASP.NET MVC 5 修复:

      (我的答案类似于上面的 MFC 答案,但有一些小改动)

      我还没有准备好更改为 Json.NET,就我而言,错误是在请求期间发生的。在我的场景中,最好的方法是修改实际的JsonValueProviderFactory,它将修复应用于全局项目,并且可以通过编辑global.cs 文件来完成。

      JsonValueProviderConfig.Config(ValueProviderFactories.Factories);
      

      添加一个 web.config 条目:

      <add key="aspnet:MaxJsonLength" value="20971520" />
      

      然后创建以下两个类

      public class JsonValueProviderConfig
      {
          public static void Config(ValueProviderFactoryCollection factories)
          {
              var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
              factories.Remove(jsonProviderFactory);
              factories.Add(new CustomJsonValueProviderFactory());
          }
      }
      

      这基本上是System.Web.Mvc 中的默认实现的精确副本,但添加了可配置的 web.config appsetting 值aspnet:MaxJsonLength

      public class CustomJsonValueProviderFactory : ValueProviderFactory
      {
      
          /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
          /// <returns>A JSON value-provider object for the specified controller context.</returns>
          /// <param name="controllerContext">The controller context.</param>
          public override IValueProvider GetValueProvider(ControllerContext controllerContext)
          {
              if (controllerContext == null)
                  throw new ArgumentNullException("controllerContext");
      
              object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
              if (deserializedObject == null)
                  return null;
      
              Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
              CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);
      
              return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
          }
      
          private static object GetDeserializedObject(ControllerContext controllerContext)
          {
              if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                  return null;
      
              string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
              if (string.IsNullOrEmpty(fullStreamString))
                  return null;
      
              var serializer = new JavaScriptSerializer()
              {
                  MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
              };
              return serializer.DeserializeObject(fullStreamString);
          }
      
          private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
          {
              IDictionary<string, object> strs = value as IDictionary<string, object>;
              if (strs != null)
              {
                  foreach (KeyValuePair<string, object> keyValuePair in strs)
                      CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
      
                  return;
              }
      
              IList lists = value as IList;
              if (lists == null)
              {
                  backingStore.Add(prefix, value);
                  return;
              }
      
              for (int i = 0; i < lists.Count; i++)
              {
                  CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]);
              }
          }
      
          private class EntryLimitedDictionary
          {
              private static int _maximumDepth;
      
              private readonly IDictionary<string, object> _innerDictionary;
      
              private int _itemCount;
      
              static EntryLimitedDictionary()
              {
                  _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
              }
      
              public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
              {
                  this._innerDictionary = innerDictionary;
              }
      
              public void Add(string key, object value)
              {
                  int num = this._itemCount + 1;
                  this._itemCount = num;
                  if (num > _maximumDepth)
                  {
                      throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
                  }
                  this._innerDictionary.Add(key, value);
              }
          }
      
          private static string MakeArrayKey(string prefix, int index)
          {
              return string.Concat(prefix, "[", index.ToString(CultureInfo.InvariantCulture), "]");
          }
      
          private static string MakePropertyKey(string prefix, string propertyName)
          {
              if (string.IsNullOrEmpty(prefix))
              {
                  return propertyName;
              }
              return string.Concat(prefix, ".", propertyName);
          }
      
          private static int GetMaximumDepth()
          {
              int num;
              NameValueCollection appSettings = ConfigurationManager.AppSettings;
              if (appSettings != null)
              {
                  string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
                  if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
                  {
                      return num;
                  }
              }
              return 1000;
          }
      
          private static int GetMaxJsonLength()
          {
              int num;
              NameValueCollection appSettings = ConfigurationManager.AppSettings;
              if (appSettings != null)
              {
                  string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
                  if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
                  {
                      return num;
                  }
              }
              return 1000;
          }
      }
      

      【讨论】:

      • 谢谢它的工作......非常感谢@Maxim Gershkovich
      【解决方案11】:

      你不需要做 web.config 您可以在传递列表的捕获值期间使用短属性 例如 声明一个模型,如

      public class BookModel
          {
              public decimal id { get; set; }  // 1 
      
              public string BN { get; set; } // 2 Book Name
      
              public string BC { get; set; } // 3 Bar Code Number
      
              public string BE { get; set; } // 4 Edition Name
      
              public string BAL { get; set; } // 5 Academic Level
      
              public string BCAT { get; set; } // 6 Category
      }
      

      在这里我使用短比例,比如 BC =条形码 BE=书版等

      【讨论】:

      • 如果大量数据在属性值中,这将无济于事
      【解决方案12】:

      属性魔法怎么样?

      [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
      public class MaxJsonSizeAttribute : ActionFilterAttribute
      {
          // Default: 10 MB worth of one byte chars
          private int maxLength = 10 * 1024 * 1024;
      
          public int MaxLength
          {
              set
              {
                  if (value < 0) throw new ArgumentOutOfRangeException("value", "Value must be at least 0.");
      
                  maxLength = value;
              }
              get { return maxLength; }
          }
      
          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
              JsonResult json = filterContext.Result as JsonResult;
              if (json != null)
              {
                  if (maxLength == 0)
                  {
                      json.MaxJsonLength = int.MaxValue;
                  }
                  else
                  {
                      json.MaxJsonLength = maxLength;
                  }
              }
          }
      }
      

      然后您可以使用全局过滤器配置或控制器/动作方式全局应用它。

      【讨论】:

      • 很好的答案。很好地使用自定义属性。想知道是否有特定(技术)原因将默认值设置为 10 MB 的一字节字符而不是 Max (int.MaxValue)?
      • @Josh 不,没有任何特殊原因。
      【解决方案13】:

      我们不需要任何服务器端更改。 您只能通过 web.config 文件修改来解决此问题 这对我有帮助。试试这个

      <appSettings>
       <add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" />
      <add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
      </appSettings>  
      
      and   
      
      <system.web.extensions>
      <scripting>
        <webServices>
          <jsonSerialization maxJsonLength="2147483647"/>
        </webServices>
      </scripting>
      

      【讨论】:

        【解决方案14】:

        只需在 MVC 的 Action 方法中设置 MaxJsonLength 属性

        JsonResult json= Json(classObject, JsonRequestBehavior.AllowGet);
        json.MaxJsonLength = int.MaxValue;
        return json;
        

        【讨论】:

          【解决方案15】:

          如果您在 View 中遇到此类问题,您可以使用以下方法解决。这里使用了 Newtonsoft 包。

          @using Newtonsoft.Json
          <script type="text/javascript">
              var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
          </script>
          

          【讨论】:

          • 这是否意味着如果我使用 Json.NET,我不必担心最大长度?我认为没有办法在 Json.NET 中设置最大长度,所以我希望它开箱即用。
          • 优秀的答案,谢谢!这在我尝试加载对象时也有效。
          【解决方案16】:

          如果这个 maxJsonLength 值是一个 int 那么它的 int 32bit/64bit/16bit 有多大......我只是想确定我可以设置为我的 maxJsonLength 的最大值是多少

          <scripting>
                  <webServices>
                      <jsonSerialization maxJsonLength="2147483647">
                      </jsonSerialization>
                  </webServices>
              </scripting>
          

          【讨论】:

            【解决方案17】:

            我建议将其设置为 Int32.MaxValue。

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = Int32.MaxValue;
            

            【讨论】:

            • int 是 Int32 的别名
            【解决方案18】:

            WebForms UpdatePanel 的解决方案:

            将设置添加到 Web.config:

            <configuration>
              <appSettings>
                <add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
              </appSettings>
            </configuration>
            

            https://support.microsoft.com/en-us/kb/981884

            ScriptRegistrationManager 类包含以下代码:

            // Serialize the attributes to JSON and write them out
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            
            // Dev10# 877767 - Allow configurable UpdatePanel script block length
            // The default is JavaScriptSerializer.DefaultMaxJsonLength
            if (AppSettings.UpdatePanelMaxScriptLength > 0) {
                serializer.MaxJsonLength = AppSettings.UpdatePanelMaxScriptLength;
            }  
            
            string attrText = serializer.Serialize(attrs);
            

            【讨论】:

              【解决方案19】:

              使用lib\Newtonsoft.Json.dll

              public string serializeObj(dynamic json) {        
                  return JsonConvert.SerializeObject(json);
              }
              

              【讨论】:

                【解决方案20】:

                你可以把这行写进Controller

                json.MaxJsonLength = 2147483644;
                

                您也可以将此行写入web.config

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

                `

                为了安全起见,请同时使用。

                【讨论】:

                  【解决方案21】:

                  我在 ASP.NET Web 窗体中遇到了这个问题。它完全忽略了 web.config 文件设置,所以我这样做了:

                          JavaScriptSerializer serializer = new JavaScriptSerializer();
                  
                          serializer.MaxJsonLength = Int32.MaxValue; 
                  
                          return serializer.Serialize(response);
                  

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

                  【讨论】:

                  • 这对你有用吗?你把这段代码放在哪里了?
                  • 我们的问题是因为我们有一个允许 HTML 的文本区域,并且人们将图像嵌入为 HTML,这导致条目变得非常大并且 JSON 序列化程序失败。我猜如果可以做到,用户会做到的......
                  • 请描述我们应该把这段代码放在哪里...@Flea
                  • @KorayDurudogan - 我把它放在返回响应的 Ajax 方法中,所以放在我的控制器中。希望有帮助!
                  • 我不是在挑战您的回答,而是试图更好地了解有哪些更好的方法。我有一个查询,根据用户的标准将确定结果大小。我返回一个JsonResult,我返回一个excel文件有关系吗?
                  【解决方案22】:

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

                  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();
                  

                  【讨论】:

                  • 这似乎是一个骇人听闻的解决方案,但无论如何都很有趣。我发现它很有用谢谢!对我来说,在 apsnet mvc 5 控制器中,我必须从命名空间中删除“当前”。我做了一些调整:string confString = HttpContext.Request.ApplicationPath.ToString(); var conf = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(confString); var section = (System.Web.Configuration.ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization"); section.MaxJsonLength = int.MaxValue; conf.Save();
                  【解决方案23】:

                  如果您从 MVC 中的 MiniProfiler 收到此错误,则可以通过将属性 MiniProfiler.Settings.MaxJsonResponseSize 设置为所需值来增加该值。默认情况下,这个工具似乎会忽略 config 中设置的值。

                  MiniProfiler.Settings.MaxJsonResponseSize = 104857600;
                  

                  礼貌mvc-mini-profiler

                  【讨论】:

                    【解决方案24】:

                    刚刚碰到这个。我收到了超过 6,000 条记录。刚刚决定我只是做一些分页。如,我在我的 MVC JsonResult 端点中接受页码,默认为 0,因此没有必要,如下所示:

                    public JsonResult MyObjects(int pageNumber = 0)
                    

                    然后不要说:

                    return Json(_repository.MyObjects.ToList(), JsonRequestBehavior.AllowGet);
                    

                    我说:

                    return Json(_repository.MyObjects.OrderBy(obj => obj.ID).Skip(1000 * pageNumber).Take(1000).ToList(), JsonRequestBehavior.AllowGet);
                    

                    这很简单。然后,在 JavaScript 中,而不是这样:

                    function myAJAXCallback(items) {
                        // Do stuff here
                    }
                    

                    我反而说:

                    var pageNumber = 0;
                    function myAJAXCallback(items) {
                        if(items.length == 1000)
                            // Call same endpoint but add this to the end: '?pageNumber=' + ++pageNumber
                        }
                        // Do stuff here
                    }
                    

                    并将您的记录附加到您对它们所做的任何事情中。或者等到所有调用完成后再将结果拼凑在一起。

                    【讨论】:

                      【解决方案25】:

                      对于那些在 MVC3 中遇到 JSON 自动反序列化以用于模型绑定并且太大的问题的人,这里有一个解决方案。

                      1. 将 JsonValueProviderFactory 类的代码从 MVC3 源代码复制到一个新类中。
                      2. 在反序列化对象之前添加一行以更改最大 JSON 长度。
                      3. 用您修改过的新类替换 JsonValueProviderFactory 类。

                      感谢http://blog.naver.com/techshare/100145191355https://gist.github.com/DalSoft/1588818 为我指明了正确的方向。第一个站点上的最后一个链接包含解决方案的完整源代码。

                      【讨论】:

                        【解决方案26】:

                        您可以像其他人所说的那样在配置中设置它,或者您可以在序列化程序的单个实例上进行设置,例如:

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

                        【讨论】:

                          【解决方案27】:

                          我修好了。

                          //your Json data here
                          string json_object="........";
                          JavaScriptSerializer jsJson = new JavaScriptSerializer();
                          jsJson.MaxJsonLength = 2147483644;
                          MyClass obj = jsJson.Deserialize<MyClass>(json_object);
                          

                          效果很好。

                          【讨论】:

                          • 太棒了!这是唯一对我有用的解决方案,而且它更好,因为它不是全球性的变化。谢谢!
                          • jsJson.MaxJsonLength = 2147483644;在 Windows 窗体应用程序中为我工作
                          【解决方案28】:

                          如果在您的 web.config 中实施上述添加后,您会得到一个“无法识别的配置部分 system.web.extensions”。错误然后尝试将其添加到您的 web.config 中的 &lt;ConfigSections&gt; 部分:

                                      <sectionGroup name="system.web.extensions" type="System.Web.Extensions">
                                        <sectionGroup name="scripting" type="System.Web.Extensions">
                                              <sectionGroup name="webServices" type="System.Web.Extensions">
                                                    <section name="jsonSerialization" type="System.Web.Extensions"/>
                                              </sectionGroup>
                                        </sectionGroup>
                                  </sectionGroup>
                          

                          【讨论】:

                          • 我遇到了这个问题。但是,这个答案对我不起作用。我没有添加此处描述的 元素,而是将整个新添加的 块移到了我的 web.config 的最后... 之前。然后它起作用了。
                          • 这有帮助,但在我的情况下,我需要将您的第四行更改为 &lt;section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/&gt;,如本页所示:forums.asp.net/t/1446510.aspx/1
                          • @ClearCloud8 立即将该评论传播到整个页面。
                          【解决方案29】:

                          您可以在 web.config 文件中配置 json 请求的最大长度:

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

                          maxJsonLength 的默认值为 102400。有关详细信息,请参阅此 MSDN 页面:http://msdn.microsoft.com/en-us/library/bb763183.aspx

                          【讨论】:

                          • 这个整数中存储的值代表什么?这是某种字符数吗?我想我要问的是,为什么要使用整数?谢谢!
                          • @eaglei22 这个数字表示 maxJsonLength 可以使用多少字节。正如 M4N 提到的,102400 是默认值 (100KB)。
                          • 这对我不起作用,我没有使用网络服务。
                          【解决方案30】:

                          似乎没有“无限”的价值。默认为 2097152 个字符,相当于 4 MB 的 Unicode 字符串数据。

                          正如已经观察到的,17,000 条记录很难在浏览器中很好地使用。如果您正在呈现聚合视图,则在服务器上进行聚合并在浏览器中仅传输摘要可能会更有效。例如,考虑一个文件系统浏览器,我们只看到树的顶部,然后在我们向下钻取时发出更多请求。每个请求返回的记录数比较少。树视图表示可以很好地处理大型结果集。

                          【讨论】:

                          猜你喜欢
                          • 2016-09-05
                          • 1970-01-01
                          • 2011-10-20
                          • 2014-10-05
                          相关资源
                          最近更新 更多