An error occurred while using JSON javascriptserializer for serialization or deserialization. The length of the string exceeds the value set for the maxjsonlength attribute.

Source: Internet
Author: User
Tags stack trace

Today, we encountered such an exception. The exception information is as follows:

Type: system. invalidoperationexception, mscorlib, version = 2.0.0.0, culture = neutral, publickeytoken = b77a5c561934e089 message: Error in serialization or deserialization using JSON javascriptserializer. The length of the string exceeds the value set for the maxjsonlength attribute. Source: system. web. extensions help link: Data: system. collections. listdictionaryinternal targetsite: void serialize (system. object, system. text. stringbuilder, serializationformat) stack trace: in the system. web. script. serialization. javascriptserializer. serialize (Object OBJ, stringbuilder output, serializationformat) in system. web. script. serialization. javascriptserializer. serialize (objectobj, serializationformat) in system. web. script. serialization. javascriptserializer. serialize (Object

This exception is thrown when jsonresult is executed in MVC. According to the exception message, the serialized string exceeds the limit of maxjsonlength. It is also known that this attribute is provided by javascriptserializer, because the built-in jsonresult of MVC is serialized using javascriptserializer. I quickly searched the internet and found many children's shoes that encountered this problem. Most of the recommended solutions are to add the following configuration in Web. config and set the length of maxjsonlength.

 

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

With the automatic prompt, a few lines of code are smoothly added, which means this is a simple solution, but the following error is reported after running the website:

Analyzer error message:Unrecognized configuration section system. Web. Extensions.
This seems to happen again when the family does not know it. Since it cannot identify why it can be output in a smart way and started with system. Web, it cannot be identified by reason. I thought it was a spelling mistake. After further searching, it turned out that there was a lack of declarations, and the declaration of the node was enough (a large string of content ).

 

<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>

 

After the declaration is added, it runs normally, but the problem persists. No matter how many maxjsonlengths are set to be invalid, it can still run even if it is changed to 1 character. When this problem occurs, you can only search for it further. In this article, we found.

In the jsonresult code built in the MVC framework, when using javascriptserializer, the default value is used. If the value is not read from maxjsonlength, this configuration is ignored. To use the value in the configuration, only one jsonresult can be customized, And the executeresult method of the original jsonresult can be rewritten. Therefore, a configurablejsonresult is defined. The Code is as follows:

 

 

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));             }         }     }

The key is the Code marked in red to read the configuration value. Javascriptserializer has other attributes that can be configured. They are not listed and implemented. They are sufficient for the time being.

In this way, you can directly replace the original jsonresult when returning the JSON results of long characters, while also taking into account the configurable flexibility.

 

 

========================================================== ====================

Transferred from:

Http://www.cnblogs.com/shenba/archive/2012/02/03/2337050.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.