Logo

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

photo

2022年06月01日

Type : System.InvalidOperationException, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089
 
Message : 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串
的长度超过了为 maxJsonLength 属性设置的值。
 
Source : System.Web.Extensions
Help link : 
Data : System.Collections.ListDictionaryInternal
TargetSite : Void Serialize(System.Object, System.Text.StringBuilder,
SerializationFormat)
Stack Trace :    在
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj,
StringBuilder output, SerializationFormat serializationFormat)
 在 System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat)
   在 System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object
 这个异常是在执行MVC中的JsonResult的时抛出的,根据异常的Message得知是序列化的字符串超出了maxJsonLength的限制。并得知这个属性是由JavaScriptSerializer提供的,因为MVC内置的JsonResult是用JavaScriptSerializer进行序列化的。在网上快速搜索了一下,碰到这个问题的童鞋不少,大部分推荐的解决的方法都是在web.config中加入以下配置,设置maxJsonLength的长度即可。

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

View Code

在自动提示下,很顺畅的加上了几行代码,以为这是个简洁的解决方案,但是运行网站之后报以下错误:

分析器错误消息: 无法识别的配置节 system.web.extensions。
这似乎又是碰到了一家人不认识的情况,既然无法识别为什么能带智能感知的方式输出,而且是已system.web开头的,按道理不会识别不出的。以为是拼写错误,经过进一步搜索之后,原来是缺乏了声明,加上对节点的声明即可(很大一串的内容)。

<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
              <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
              <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                  <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                  <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                  <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                  <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
              </sectionGroup>
          </sectionGroup>
      </sectionGroup>

View Code

加入了声明之后,运行正常,但是问题依旧还在,而且不管maxJsonLength设置成多大都无效,就算改成1个字符,居然还能跑起来。碰到这个问题只能进一步的搜索。在这篇文章中找到了原委http://weblogs.asp.net/rashid/archive/2009/03/23/submitting-my-first-bug-after-asp-net-mvc-1-0-rtm-release.aspx

原来MVC框架内置的JsonResult代码中,在使用JavaScriptSerializer时,都是采用的默认值,没有从maxJsonLength读取值,即忽略了这个配置。要想使用配置中的值,只能自定义一个JsonResult,重写原JsonResult的ExecuteResult方法,于是定义一个ConfigurableJsonResult,代码如下:

 public class ConfigurableJsonResult : JsonResult
     {
         public override void ExecuteResult(ControllerContext context)
         {
             if (context == null)
             {
                 throw new ArgumentNullException("context");
             }
             if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                 String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
             {
                 throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
             }
 
             HttpResponseBase response = context.HttpContext.Response;
 
             if (!String.IsNullOrEmpty(ContentType))
             {
                 response.ContentType = ContentType;
             }
             else
             {
                 response.ContentType = "application/json";
             }
             if (ContentEncoding != null)
             {
                 response.ContentEncoding = ContentEncoding;
             }
             if (Data != null)
             {
                 JavaScriptSerializer serializer = new JavaScriptSerializer();
 
                 ScriptingJsonSerializationSection section = ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as ScriptingJsonSerializationSection;
            
                 if (section != null)
                 {
                     serializer.MaxJsonLength = section.MaxJsonLength;
                     serializer.RecursionLimit = section.RecursionLimit;
                 }
 
                 response.Write(serializer.Serialize(Data));
             }
         }
     }

View Code

这样在返回长字符内容的json结果时,直接替换原JsonResult即可,同时也兼顾了可配置的灵活性。

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
本文为原创文章,请注意保留出处!

如果表单中有多个同名表单,即name一样时,只能提交一个,而不是多个。分析了一下是因为监听表单序列时...layUI提交多个相同name的值

热门文章

西游记之大圣归来 《西游记之大圣归来》是根据中国传统神话故事《西游记》进行拓展和演绎的3D动画电影。由横店影视、天空之城、燕城十月与微影时代作为出品方,高路动画、恭梓兄弟、世纪长龙、山东影视、东台龙行盛世、淮安西游产业与永康壹禾作为联合出品方出品,田晓鹏执导,张磊、林子杰、刘九容和童自荣等联袂配音。影片讲述了已于五行山下寂寞沉潜五百年的孙悟空被儿时的唐僧——俗名江流儿的小和尚误打误撞地解除了封印,在相互陪伴的冒险之旅中找回初心,完成自我救赎的故事。 作者:Pastore Antonio
1448 浏览量
常用的Centos操作Shell命令 玩WordPress的时候经常会接触到一些常用的命令,老是忘记……人年纪大了就是不给力啊。浏览量:...常用的Centos操作Shell命令 作者:Pastore Antonio
1387 浏览量
ffmpeg+srs 实现直播流 这篇文章是我在做直播流的时候收集的所有素材,没有太多的整理,都放到了脑袋里面了,之后有时间了再整理成...ffmpeg+srs实现直播流 作者:Pastore Antonio
1387 浏览量
项目十大管理和五大过程 PMBOK五大过程组是什么?PMBOK五大过程组是:启动过程、规划过程、执行过程、监...项目十大管理和五大过程 作者:Pastore Antonio
1363 浏览量
[ Office 365 开发系列 ] 身份认证 前言本文完全原创,转载请说明出处,希望对大家有用。通常我们在开发一个应用时,需要考虑用户身份认证...[Office365开发系列]身份认证 作者:Pastore Antonio
1357 浏览量