我正在使用jQuery的自动完成功能。当我试图检索超过17000条记录的列表(每个记录不会超过10个字符长度)时,它超过了长度并抛出错误:
异常信息: 异常类型:InvalidOperationException 异常消息:使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过maxJsonLength属性设置的值。
我可以在web.config中设置maxJsonLength的无限长度吗?如果不是,我可以设置的最大长度是多少?
我正在使用jQuery的自动完成功能。当我试图检索超过17000条记录的列表(每个记录不会超过10个字符长度)时,它超过了长度并抛出错误:
异常信息: 异常类型:InvalidOperationException 异常消息:使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过maxJsonLength属性设置的值。
我可以在web.config中设置maxJsonLength的无限长度吗?如果不是,我可以设置的最大长度是多少?
当前回答
你可以把这一行写进Controller
json.MaxJsonLength = 2147483644;
您也可以将这一行写入web.config
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
`
为了安全起见,两者都用。
其他回答
如果你正在使用MVC 4,一定要看看这个答案。
如果你仍然收到错误:
在web.config中将maxJsonLength属性设置为最大值之后 你知道你的数据长度小于这个值 并且您没有使用web服务方法进行JavaScript序列化
你的问题可能是:
MaxJsonLength属性的值仅应用于异步通信层用于调用Web服务方法的内部JavaScriptSerializer实例。(MSDN: ScriptingJsonSerializationSection。MaxJsonLength属性)
基本上,当从web方法调用时,“内部”JavaScriptSerializer尊重maxJsonLength的值;直接使用JavaScriptSerializer(或通过MVC action-method/Controller使用)不尊重maxJsonLength属性,至少不尊重web.config的systemwebextension .scripting. webservices . jsonserialization部分。特别是,Controller.Json()方法不尊重配置设置!
作为一种变通方法,你可以在你的控制器(或任何地方)中执行以下操作:
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论坛答案的解释。
我遵循了vestial的答案,得到了这个解决方案:
当我需要将一个大的json发送到控制器中的一个动作时,我会得到著名的“使用json JavaScriptSerializer进行反序列化期间错误”。字符串的长度超过maxJsonLength属性设置的值。\r\n参数名称:输入值提供程序”。
我所做的是创建一个新的ValueProviderFactory, LargeJsonValueProviderFactory,并设置MaxJsonLength = Int32。GetDeserializedObject方法中的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方法中,用新的ValueProviderFactory替换ValueProviderFactory:
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);
}
我们不需要任何服务器端更改。你只能通过web修改这个问题。配置文件 这对我很有帮助。试试这个
<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>
如果你从MVC中的MiniProfiler中得到这个错误,那么你可以通过设置属性MiniProfiler. settings . maxjsonresponsesize来增加这个值。默认情况下,该工具似乎忽略配置中设置的值。
MiniProfiler.Settings.MaxJsonResponseSize = 104857600;
礼貌mvc-mini-profiler。
我使用这个,它为剑道网格读取请求工作。
{
//something
var result = XResult.ToList().ToDataSourceResult(request);
var rs = Json(result, JsonRequestBehavior.AllowGet);
rs.MaxJsonLength = int.MaxValue;
return rs;
}