Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 我可以在web.config中设置maxJsonLength的无限长度吗?_Asp.net_Asp.net Mvc_Json - Fatal编程技术网

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

Asp.net 我可以在web.config中设置maxJsonLength的无限长度吗?,asp.net,asp.net-mvc,json,Asp.net,Asp.net Mvc,Json,我正在使用jQuery的自动完成功能。当我试图检索超过17000条记录(每条记录的长度不超过10个字符)的列表时,它超出了长度并抛出错误: 异常信息: 异常类型:InvalidOperationException 异常消息:使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过了maxJsonLength属性上设置的值 我可以在web.config中为maxJsonLength设置无限长度吗?如果没有,我可以设置的最大长度是多少?注意:此答案仅适用于W

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

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


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

注意:此答案仅适用于Web服务,如果您从控制器方法返回JSON,请确保您也阅读了下面的答案:


该属性不能是无限制的,它是一个默认为102400(100k)的整数属性

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

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

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

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


maxJsonLength的默认值为102400。有关更多详细信息,请参阅此MSDN页面:

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


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

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


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

如果在web.config中实现上述添加后,您得到“无法识别的配置节system.web.extensions”。错误,请尝试在
节中将其添加到web.config中:

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

如果您使用的是MVC4,请务必也签出


如果您仍然收到错误:

  • 在web.config中将
    maxJsonLength
    属性设置为其最大值后
  • 您知道数据的长度小于此值
  • 而且您没有使用web服务方法进行JavaScript序列化
您的问题可能是:

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

基本上,“internal”
JavaScriptSerializer
在从web方法调用时尊重
maxJsonLength
的值;直接使用
JavaScriptSerializer
(或通过MVC操作方法/控制器使用)不符合
maxJsonLength
属性,至少不符合web.config的
systemWebExtensions.scripting.webServices.jsonSerialization
部分。特别是,方法不遵守配置设置

作为一种解决方法,您可以在控制器内(或任何地方)执行以下操作:


这个答案是我的解释。

我修正了它

//your Json data here
string json_object="........";
JavaScriptSerializer jsJson = new JavaScriptSerializer();
jsJson.MaxJsonLength = 2147483644;
MyClass obj = jsJson.Deserialize<MyClass>(json_object);
//这里是您的Json数据
字符串json_object=“……”;
JavaScriptSerializer jsJson=新的JavaScriptSerializer();

jsJson.MaxJsonLength=2147483644; MyClass obj=jsjsjson.Deserialize(json_对象);
在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
);

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

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

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

  • 将JsonValueProviderFactory类的代码从MVC3源代码复制到新类中
  • 在反序列化对象之前,添加一行更改JSON的最大长度
  • 用新的修改类替换JsonValueProviderFactory类

  • 感谢并为我指明了正确的方向。第一个站点上的最后一个链接包含解决方案的完整源代码。

    刚刚遇到这个问题。我有6000多张唱片。我刚决定做一些传呼。如中所示,我在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
    }
    

    并将您的记录附加到您最初使用它们所做的任何事情中。或者只需等待所有调用完成并将结果拼凑在一起。

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

    MiniProfiler.Settings.MaxJsonResponseSize = 104857600;
    

    礼貌。

    我在ASP.NET Web表单中遇到了这个问题。它完全忽略了web.config文件
            JavaScriptSerializer serializer = new JavaScriptSerializer();
    
            serializer.MaxJsonLength = Int32.MaxValue; 
    
            return serializer.Serialize(response);
    
    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();
    
    json.MaxJsonLength = 2147483644;
    
    <configuration>
      <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="2147483647">
                </jsonSerialization>
            </webServices>
        </scripting>
      </system.web.extensions>
    
    public string serializeObj(dynamic json) {        
        return JsonConvert.SerializeObject(json);
    }
    
    <configuration>
      <appSettings>
        <add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
      </appSettings>
    </configuration>
    
    // 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);
    
       public ActionResult/JsonResult getData()
       {
          var jsonResult = Json(superlargedata, JsonRequestBehavior.AllowGet);
          jsonResult.MaxJsonLength = int.MaxValue;
          return jsonResult;
        }
    
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    serializer.MaxJsonLength = Int32.MaxValue;
    
    <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="2147483647">
                </jsonSerialization>
            </webServices>
        </scripting>
    
    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;
         }
      }
    }
    
    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);
    }
    
    [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;
                }
            }
        }
    }
    
    @using Newtonsoft.Json
    <script type="text/javascript">
        var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
    </script>
    
    JsonResult json= Json(classObject, JsonRequestBehavior.AllowGet);
    json.MaxJsonLength = int.MaxValue;
    return json;
    
    <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>
    
    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
    }
    
    JsonValueProviderConfig.Config(ValueProviderFactories.Factories);
    
    <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());
        }
    }
    
    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;
        }
    }
    
     JsonResult result = Json(r);
     result.MaxJsonLength = Int32.MaxValue;
     result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
     return result;
    
    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
        };
    }
    
    protected internal JsonResult Json(object data)
    {
        return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
    }
    
    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
    
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    if (MaxJsonLength.HasValue)
    {
        serializer.MaxJsonLength = MaxJsonLength.Value;
    }
    
    if (RecursionLimit.HasValue)
    {
        serializer.RecursionLimit = RecursionLimit.Value;
    }
    
    response.Write(serializer.Serialize(Data));