[ArgumentException: 使用 JSON JavaScriptSerializer 序列化或还原序列化期间发生错误。字符串的长度超过在 maxJsonLength 属性上设定的值。
参数名称: input]
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +168
System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +213
System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +16
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +69
System.Web.Mvc.ControllerBase.get_ValueProvider() +30  

由于前端 Post 到 Action 的参数太大,超过了2M,还没进入后台的 Action 方法就报错了。这个问题困扰了很久,一直未解决。网上找了几个方法都无效。

在 web.config 中加入这些,没有作用:

<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" />
<add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
</appSettings>

在 web.config 中加入这些,也没有作用:

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

仔细看了一下异常信息,发现,是在System.Web.Mvc.JsonValueProviderFactory 里调用的 JavaScriptSerializer:

于是查了一下 ,发现 JsonValueProviderFactory 在 System.Web.Mvc.dll 程序集里的:

反编译 System.Web.Mvc.dll 找到 JsonValueProviderFactory 类:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Web.Mvc.Properties;
using System.Web.Script.Serialization;
namespace System.Web.Mvc
{
public sealed class JsonValueProviderFactory : ValueProviderFactory
{
private class EntryLimitedDictionary
{
private static int _maximumDepth = JsonValueProviderFactory.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 > JsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
{
throw new InvalidOperationException(MvcResources.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;
}
}
private static void AddToBackingStore(JsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> dictionary = value as IDictionary<string, object>;
if (dictionary != null)
{
foreach (KeyValuePair<string, object> current in dictionary)
{
JsonValueProviderFactory.AddToBackingStore(backingStore, JsonValueProviderFactory.MakePropertyKey(prefix, current.Key), current.Value);
}
return;
}
IList list = value as IList;
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
JsonValueProviderFactory.AddToBackingStore(backingStore, JsonValueProviderFactory.MakeArrayKey(prefix, i), list[i]);
}
return;
}
backingStore.Add(prefix, value);
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
return null;
}
StreamReader streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string text = streamReader.ReadToEnd();
if (string.IsNullOrEmpty(text))
{
return null;
}
// 问题就出在这里,没有给 javaScriptSerializer.MaxJsonLength 赋值,其默认值是 2097152 字节,即2M
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
return javaScriptSerializer.DeserializeObject(text);
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object deserializedObject = JsonValueProviderFactory.GetDeserializedObject(controllerContext);
if (deserializedObject == null)
{
return null;
}
Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
JsonValueProviderFactory.EntryLimitedDictionary backingStore = new JsonValueProviderFactory.EntryLimitedDictionary(dictionary);
JsonValueProviderFactory.AddToBackingStore(backingStore, string.Empty, deserializedObject);
return new DictionaryValueProvider<object>(dictionary, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
{
return prefix + "." + propertyName;
}
return propertyName;
}
}
}

在 JavaScriptSerializer 没有设置 MaxJsonLength,默认值是 2097152 字节,即2M。 

解决此问题的方法就是 把 javaScriptSerializer.MaxJsonLength = int.MaxValue; (int.MaxValue 值是 2147483647 字节,即2048M)

自己重写类 JsonValueProviderFactory 命名为 MyJsonValueProviderFactory:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Web.Mvc;
using System.Web.Mvc.Properties;
using System.Web.Script.Serialization;
namespace XXX
{
public sealed class MyJsonValueProviderFactory : ValueProviderFactory
{
private class EntryLimitedDictionary
{
private static int _maximumDepth = 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 > _maximumDepth)
{
//throw new InvalidOperationException(MvcResources.JsonValueProviderFactory_RequestTooLarge);
throw new InvalidOperationException("itemCount is over maximumDepth");
}
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;
}
} private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> dictionary = value as IDictionary<string, object>;
if (dictionary != null)
{
foreach (KeyValuePair<string, object> current in dictionary)
{
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 object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
return null;
}
StreamReader streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string text = streamReader.ReadToEnd();
if (string.IsNullOrEmpty(text))
{
return null;
}
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
// 解决这个问题:
// 使用 JSON JavaScriptSerializer 序列化或还原序列化期间发生错误。字符串的长度超过在 maxJsonLength 属性上设定的值。
javaScriptSerializer.MaxJsonLength = int.MaxValue;
// ----------------------------------------
return javaScriptSerializer.DeserializeObject(text);
} public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object deserializedObject = GetDeserializedObject(controllerContext);
if (deserializedObject == null)
{
return null;
}
Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
EntryLimitedDictionary backingStore = new EntryLimitedDictionary(dictionary);
AddToBackingStore(backingStore, string.Empty, deserializedObject);
return new DictionaryValueProvider<object>(dictionary, CultureInfo.CurrentCulture);
} private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
} private static string MakePropertyKey(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
{
return prefix + "." + propertyName;
}
return propertyName;
}
}
}

然后在 Global.asax 中的 Application_Start() 方法里,加入如下代码,用 MyJsonValueProviderFactory 类代替 System.Web.Mvc.dll 程序集中的 JsonValueProviderFactory 类。

ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());

至此,.NET MVC 超出 maxJsonLength 的问题终于解决了!

  

  

.NET MVC JSON JavaScriptSerializer 字符串的长度超过 maxJsonLength 值问题的解决的更多相关文章

  1. JSON JavaScriptSerializer 字符串的长度超过了为 maxJsonLength 属性设置的值。

    1.序列化: 以下代码在对象过大时会报错:进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. //jsonObj比较大的时候会报错 var serialize ...

  2. .net MVC 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错,字符串的长度超过了为 maxJsonLength 属性设置的值

    在.net mvc的controller中,方法返回JsonResult,一般我们这么写: [HttpPost] public JsonResult QueryFeature(string url, ...

  3. JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值

    在.net mvc的controller中,方法返回JsonResult,一般我们这么写:   [HttpPost]   public JsonResult QueryFeature(string u ...

  4. ASP.NET MVC Json()处理大数据异常解决方法,字符串的长度超过了为 maxJsonLength

    问题: 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. <system.web.exten ...

  5. 使用JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength属性

    "/"应用程序中的服务器错误.使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. ...

  6. MVC JSON JavaScriptSerializer 进行序列化或反序列化时出错

    MVC control中返回json格式数据一般都是如下格式 [HttpPost] public ActionResult CaseAudit(string name) { var data =&qu ...

  7. 此请求的查询字符串的长度超过配置的 maxQueryStringLength 值

    异常详细信息: System.Web.HttpException: 此请求的查询字符串的长度超过配置的maxQueryStringLength 值. 我碰到此问题出现的原因是重写了HttpModule ...

  8. Xrm.Utility.openEntityForm 时404.15 maxQueryString 错误 和 长度超过maxQueryStringLength值 错误

    最近的项目里用到Xrm.Utility.openEntityForm 创建新记录时分别碰到以下错误: 以及 这两个错误都是因为想传递给表单的参数太多导致的url 查询参数太长导致的,前者是因为iis的 ...

  9. 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。

    解决办法是在web.config增加如下节点到<configuration>下 <system.web.extensions> <scripting> <we ...

随机推荐

  1. centos7下zabbix记录

    Zabbixrpm -ivh http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm - ...

  2. MFC图片操作

    根据MFC要操作图片的来源,可分为以下两类: 一.非动态显示图片(即图片先通过资源管理器载入,有一个固定ID) 二.动态载入图片(即只需要在程序中指定图片的路径即可载入) 一.非动态显示图片 1.传送 ...

  3. nodejs异步请求重试策略总结

    对于node开发同学经常要处理异步请求,然后根据请求的结果或请求成功后的状态码做不同的策略处理,众多策略中最常用的一种就是重试策略.针对重试策略我们往往还需要设定一定的规则,如重试次数.重试时间间隔. ...

  4. 吴恩达机器学习笔记1-单变量线性回归(Linear Regression with One Variable)

    在监督学习中我们有一个数据集,这个数据集被称训练集.

  5. system libzip must be upgraded to version >= 0.11

    PHP当前最新版本是PHP7.3,今天在尝试安装的过程中报如下错误: system libzip must be upgraded to version >= 0.11, 根据提示我们可以清楚的 ...

  6. Tomcat 的 server.xml 文件详解

    文件内容解读 <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apac ...

  7. Kali学习笔记21:缓冲区溢出实验(漏洞发现)

    上一篇文章,我已经做好了缓冲区溢出实验的准备工作: https://www.cnblogs.com/xuyiqing/p/9835561.html 下面就是Kali虚拟机对缓冲区溢出的测试: 已经知道 ...

  8. word标题文字居中浅谈

    在Word排版时,要将标题在文档居中,是有区别的,如下图 在回车键后,在选择标题居中,我们常认为标题就是在整个文档居中了,但是实际上只是在回车键到右边区域居中而已,如上图红色方块居中. 只有在标题文字 ...

  9. sql server 性能调优之 CPU消耗最大资源分析1 (自sqlserver服务启动以后)

    一. 概述 上次在介绍性能调优中讲到了I/O的开销查看及维护,这次介绍CPU的开销及维护, 在调优方面是可以从多个维度去发现问题如I/O,CPU,  内存,锁等,不管从哪个维度去解决,都能达到调优的效 ...

  10. app 性能

    Android App优化之性能分析工具 https://www.jianshu.com/p/da2a4bfcba68 -------------- 系列文: 背景:Android App优化, 要怎 ...