Can I set an unlimited length for maxJsonLength in web.config?

后端 未结 29 3157
礼貌的吻别
礼貌的吻别 2020-11-21 06:43

I am using the autocomplete feature of jQuery. When I try to retrieve the list of more then 17000 records (each won\'t have more than 10 char length), it\'s exceeding the le

相关标签:
29条回答
  • 2020-11-21 07:37

    you can write this line into Controller

    json.MaxJsonLength = 2147483644;
    

    you can also write this line into web.config

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

    `

    To be on the safe side, use both.

    0 讨论(0)
  • 2020-11-21 07:37

    If you are getting this error from the MiniProfiler in MVC then you can increase the value by setting the property MiniProfiler.Settings.MaxJsonResponseSize to the desired value. By default, this tool seems to ignore the value set in config.

    MiniProfiler.Settings.MaxJsonResponseSize = 104857600;
    

    Courtesy mvc-mini-profiler.

    0 讨论(0)
  • 2020-11-21 07:37

    Just ran into this. I'm getting over 6,000 records. Just decided I'd just do some paging. As in, I accept a page number in my MVC JsonResult endpoint, which is defaulted to 0 so it's not necessary, like so:

    public JsonResult MyObjects(int pageNumber = 0)
    

    Then instead of saying:

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

    I say:

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

    It's very simple. Then, in JavaScript, instead of this:

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

    I instead say:

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

    And append your records to whatever you were doing with them in the first place. Or just wait until all the calls finish and cobble the results together.

    0 讨论(0)
  • 2020-11-21 07:40

    You do not need to do with web.config You can use short property during catch value of the passing list For example declare a model like

    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
    }
    

    here i use short proporties like BC =barcode BE=book edition and so on

    0 讨论(0)
  • 2020-11-21 07:43

    Alternative ASP.NET MVC 5 Fix:

    (Mine is similar to MFCs answer above with a few small changes)

    I wasn't ready to change to Json.NET just yet and in my case the error was occurring during the request. Best approach in my scenario was modifying the actual JsonValueProviderFactory which applies the fix to the global project and can be done by editing the global.cs file as such.

    JsonValueProviderConfig.Config(ValueProviderFactories.Factories);
    

    add a web.config entry:

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

    and then create the two following classes

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

    This is basically an exact copy of the default implementation found in System.Web.Mvc but with the addition of a configurable web.config appsetting value 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:44

    How about some attribute magic?

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

    Then you could either apply it globally using the global filter configuration or controller/action-wise.

    0 讨论(0)
提交回复
热议问题