Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Gavin Holyday 2 posts 92 karma points
    Jan 07, 2020 @ 12:06
    Gavin Holyday
    0

    Backoffice angular file upload maxJsonLength exceeded

    Hi, I was wondering if I could get some assistance with an issue I'm having. I have created an angular file upload form in the back office to create nodes from a csv using the umbraco API, however the files uploaded are in excess of 4MB and when I try to submit I receive the following error: Error during serialization using the json javascriptserializer. The length of the string exceeds the value set on the maxJsonLength property.

    I have tried updating the following values in the web config to 2147483644 as all answers I could find in the forum point to this, but I still get the error:

    <webServices>
            <!-- Update this value to change the value to
                        a larger value that can accommodate your JSON
                        strings -->
            <jsonSerialization maxJsonLength="2147483644" />
          </webServices>
    
    <requestFiltering>
            <requestLimits maxAllowedContentLength="2147483644" />
          </requestFiltering>
    
    <httpRuntime requestValidationMode="2.0" enableVersionHeader="false" targetFramework="4.7.2" maxRequestLength="2147483644" fcnMode="Single" />
    
  • Owen Parsons 5 posts 75 karma points
    Jan 10, 2020 @ 16:29
    Owen Parsons
    0

    Have just come across the same issue, any solutions out there?

  • Gavin Holyday 2 posts 92 karma points
    Jan 10, 2020 @ 16:54
    Gavin Holyday
    100

    I had to add override the default serializer to resolve this in the end.

    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;
            }
        }
    }
    
    public class StartupComponent : IComponent
    {
        public void Initialize()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
    
            //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);
        }       
    
        public void Terminate()
        {
        }
    
Please Sign in or register to post replies

Write your reply to:

Draft