首页 > Web开发 > 详细

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

时间:2014-04-12 10:50:37      阅读:847      评论:0      收藏:0      [点我收藏+]

异常信息如下:

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

 

还必须重写JsonResult这个类:

bubuko.com,布布扣
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));
            }
        }
    }
bubuko.com,布布扣

 

 

测试后可以正常使用。

 

参考:

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

MVC中JSON字符长度超出限制的异常处理,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/sherlock99/p/3659759.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!