MVC中JSON字符长度超出限制的异常处理

异常信息如下:

使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。
 
这个异常是在执行MVC中的JsonResult的时抛出的,根据异常的Message得知是序列化的字符串超出了maxJsonLength的限制。并得知这个属性是由JavaScriptSerializer提供的,因为MVC内置的JsonResult是用JavaScriptSerializer进行序列化的。
 
单纯在web.config中加入下列配置节无效:
<system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="20971520"/>
           </webServices>
       </scripting>
</system.web.extensions>

还必须重写JsonResult这个类:

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

测试后可以正常使用。

参考:

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

http://weblogs.asp.net/rashid/archive/2009/03/23/submitting-my-first-bug-after-asp-net-mvc-1-0-rtm-release.aspx

原文地址:https://www.cnblogs.com/sherlock99/p/3659759.html