我可以在web.config中设置maxJsonLength的无限长度吗?

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

exception信息:
exceptiontypes:InvalidOperationException
exception消息:在使用JSON JavaScriptSerializer序列化或反序列化期间出错。 string的长度超过maxJsonLength属性中设置的值。

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

注意:这个答案只适用于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> 

如果您使用的是MVC 4 ,那么一定要查看这个答案


如果您仍然收到错误:

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

你的问题可能是:

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

基本上,“内部” JavaScriptSerializer尊重maxJsonLength从web方法调用时的值; 直接使用JavaScriptSerializer (或通过MVC操作方法/控制器使用)并不尊重maxJsonLength属性,至less不是来自web.config的maxJsonLength部分。

作为一个解决方法,你可以在你的控制器(或任何真正的)中执行以下操作:

 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论坛答案的解释。

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

在你的控制器。

你可以在你的web.config文件中configurationjson请求的最大长度:

 <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

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

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

当然总的来说这是可怕的做法。 如果您在Web服务调用中发送这么多的数据,则应该采用不同的方法。

我修好了它。

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

它工作得很好。

如果在web.config中实现上述添加之后,您会收到“无法识别的configuration节system.web.extensions。”错误,然后尝试将其添加到您的web.config中的<ConfigSections>部分:

  <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设置之后仍然出现错误,如下所示:

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

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

 MiniProfiler.Settings.MaxJsonResponseSize = 104857600; 

提供mvc-mini-profiler 。

您可以将此行写入控制器

 json.MaxJsonLength = 2147483644; 

你也可以把这行写入web.config

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

`

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

真正的问题是你是否真的需要返回17Klogging? 你打算如何处理浏览器中的所有数据? 用户不会滚动17000行。

更好的方法是只检索“最less”logging并根据需要加载更多。

我遵循vestigal的答案,并得到这个解决scheme:

当我需要在控制器中发布一个大的json动作的时候,我会得到着名的“使用JSON JavaScriptSerializer进行反序列化时的错误,string的长度超过了maxJsonLength属性设置的值。\ r \ n参数名称:input价值提供者“。

我所做的是创build一个新的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方法中,将ValueProviderFactoryreplace为新的:

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

看起来没有“无限”的价值。 默认值为2097152个字符,相当于4 MB的Unicodestring数据。

正如已经观察到的那样,在浏览器中很难使用17000条logging。 如果您正在呈现聚合视图,则在服务器上进行聚合并仅在浏览器中传输摘要可能效率更高。 例如,考虑一个文件系统浏览器,我们只能看到树的顶部,然后在下钻时发出更多的请求。 每个请求中返回的logging数量相对较less。 树视图演示文稿可以适用于大型结果集。

刚刚碰到这个。 我收到了6000多条logging。 只是决定我只是做一些分页。 在中,我接受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 } 

并把你的logging追加到你正在和他们做的任何事情上。 或者等到所有的电话都完成并将结果拼凑在一起。

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

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

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

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

你可以像其他人那样在configuration文件中设置它,或者你可以在一个单独的序列化器实例中设置如下:

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

对于MVC3中使用JSON时出现问题的人,这些问题会自动被反序列化为模型绑定器,并且太大,这里是一个解决scheme。

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

感谢http://blog.naver.com/techshare/100145191355和https://gist.github.com/DalSoft/1588818指导我如何做到这一点的正确方向。; 第一个网站上的最后一个链接包含解决scheme的完整源代码。

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

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

如果您在View中遇到这种问题,您可以使用下面的方法来解决这个问题。 这里使用了Newtonsoft软件包。

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

使用lib\Newtonsoft.Json.dll

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

WebForms UpdatePanel解决scheme:

添加一个设置到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); 

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

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

那么一些属性魔法呢?

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

然后你可以使用“或者controller / action-wise来全局应用它。

我们不需要任何服务器端的变化。 你可以修复这个只能通过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>