.NET MVC JSON JavaScriptSerializer 字符串的长度超过 maxJsonLength 值问题的解决
[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 值问题的解决的更多相关文章
- JSON JavaScriptSerializer 字符串的长度超过了为 maxJsonLength 属性设置的值。
1.序列化: 以下代码在对象过大时会报错:进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. //jsonObj比较大的时候会报错 var serialize ...
- .net MVC 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错,字符串的长度超过了为 maxJsonLength 属性设置的值
在.net mvc的controller中,方法返回JsonResult,一般我们这么写: [HttpPost] public JsonResult QueryFeature(string url, ...
- JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值
在.net mvc的controller中,方法返回JsonResult,一般我们这么写: [HttpPost] public JsonResult QueryFeature(string u ...
- ASP.NET MVC Json()处理大数据异常解决方法,字符串的长度超过了为 maxJsonLength
问题: 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. <system.web.exten ...
- 使用JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength属性
"/"应用程序中的服务器错误.使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. ...
- MVC JSON JavaScriptSerializer 进行序列化或反序列化时出错
MVC control中返回json格式数据一般都是如下格式 [HttpPost] public ActionResult CaseAudit(string name) { var data =&qu ...
- 此请求的查询字符串的长度超过配置的 maxQueryStringLength 值
异常详细信息: System.Web.HttpException: 此请求的查询字符串的长度超过配置的maxQueryStringLength 值. 我碰到此问题出现的原因是重写了HttpModule ...
- Xrm.Utility.openEntityForm 时404.15 maxQueryString 错误 和 长度超过maxQueryStringLength值 错误
最近的项目里用到Xrm.Utility.openEntityForm 创建新记录时分别碰到以下错误: 以及 这两个错误都是因为想传递给表单的参数太多导致的url 查询参数太长导致的,前者是因为iis的 ...
- 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。
解决办法是在web.config增加如下节点到<configuration>下 <system.web.extensions> <scripting> <we ...
随机推荐
- NSInvalidArgumentException这个到底是什么意思,我到网上查了下,每个的错误都不同。
我几乎把所有的东西都注释了,但还是崩了 #import "ViewController.h" //#import "WeiBo.h" @interface Vi ...
- 导入Dynamic Web Project后程序有红叉但是可以运行
解决方法: 进入工程下的.setting文件夹,用记事本编辑org.eclipse.wst.common.project.facet.core.xml, 把<runtime name=" ...
- Gradle项目BUG
Error starting ApplicationContext. To display the auto-configuration report re-run your application ...
- Dubbo 源码分析 - 集群容错之 Router
1. 简介 上一篇文章分析了集群容错的第一部分 -- 服务目录 Directory.服务目录在刷新 Invoker 列表的过程中,会通过 Router 进行服务路由.上一篇文章关于服务路由相关逻辑没有 ...
- Java NIO工作机制简介
前言 本博客只简单介绍NIO的原理实现和基本工作流程 I/O和NIO的本质区别 NIO将填充和提取缓冲区的I/O操作转移到了操作系统 I/O 以流的方式处理数据,而 NIO 以缓冲区的方式处理数据:I ...
- localhost无法访问的问题
localhost无法访问,提示访问超时 ping localhost 和 ping 127.0.0.1 都提示一般故障,如下图 问题原因:windows防火墙故障 解决办法:关闭windows防火墙 ...
- java开发个人简历
求职意向 Java开发工程师 陈 楠 性 别:男 出生年月 :1995.07 民 族:汉族 联系方式 :159-3306-7520 学 历:本科 电子邮件 :15933067520@163.com 教 ...
- asp.net core mvc上传大文件解决方案
默认上传文件大小不超过30M 第一个问题: IIS 10.0 详细错误 - 404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求. 服务器上的请求筛选被配置为拒绝该请求 ...
- IdentityServer4(5)- 包和构建
包和构建 IdentityServer有许多Nuget包组件 IdentityServer4 nuget | github 包含IdentityServer核心对象模型.服务和中间件.默认只包含了基于 ...
- 在微信小程序中使用图表
前言:网上有许多的图表库,如:Echarts.Tau Charts.ChartJS等等,具体自行百度. 这次我们使用的是:Echarts 官方教程:点击查看 Echarts下载地址:飞机直达 1.下载 ...