public sealed classMyJsonValueProviderFactory : ValueProviderFactory
{private classEntryLimitedDictionary
{private static int _maximumDepth =GetMaximumDepth();private readonly IDictionary_innerDictionary;private int_itemCount;public EntryLimitedDictionary(IDictionaryinnerDictionary)
{this._innerDictionary =innerDictionary;
}public void Add(string key, objectvalue)
{if (++this._itemCount >_maximumDepth)
{
throw new InvalidOperationException("MvcResources.JsonValueProviderFactory_RequestTooLarge");
}this._innerDictionary.Add(key, value);
}private static intGetMaximumDepth()
{
ScriptingJsonSerializationSection section= ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") asScriptingJsonSerializationSection;if (section != null)returnsection.MaxJsonLength;return 10000;
}
}private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, objectvalue)
{
IDictionary dictionary = value as IDictionary;if (dictionary != null)
{foreach (KeyValuePair current indictionary)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, current.Key), current.Value);
}return;
}
IList list = value as IList;if (list != null)
{for (int i = 0; i < list.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), list[i]);
}return;
}
backingStore.Add(prefix, value);
}private static objectGetDeserializedObject(ControllerContext controllerContext)
{if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{return null;
}
StreamReader streamReader= newStreamReader(controllerContext.HttpContext.Request.InputStream);string text =streamReader.ReadToEnd();if (string.IsNullOrEmpty(text))
{return null;
}
JavaScriptSerializer javaScriptSerializer= newJavaScriptSerializer();//解决这个问题://使用 JSON JavaScriptSerializer 序列化或还原序列化期间发生错误。字符串的长度超过在 maxJsonLength 属性上设定的值。
javaScriptSerializer.MaxJsonLength = int.MaxValue;//----------------------------------------
returnjavaScriptSerializer.DeserializeObject(text);
}public overrideIValueProvider GetValueProvider(ControllerContext controllerContext)
{if (controllerContext == null)
{throw new ArgumentNullException("controllerContext");
}object deserializedObject =GetDeserializedObject(controllerContext);if (deserializedObject == null)
{return null;
}
Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
EntryLimitedDictionary backingStore= newEntryLimitedDictionary(dictionary);
AddToBackingStore(backingStore,string.Empty, deserializedObject);return new DictionaryValueProvider(dictionary, CultureInfo.CurrentCulture);
}private static string MakeArrayKey(string prefix, intindex)
{return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}private static string MakePropertyKey(string prefix, stringpropertyName)
{if (!string.IsNullOrEmpty(prefix))
{return prefix + "." +propertyName;
}returnpropertyName;
}
}