前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MVC中JSON字符长度超出限制的异常处理

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

原创
作者头像
sherlock99
发布2018-07-24 21:59:02
3.2K0
发布2018-07-24 21:59:02
举报
文章被收录于专栏:日常工作总结日常工作总结

异常信息如下:

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

这个异常是在执行MVC中的JsonResult的时抛出的,根据异常的Message得知是序列化的字符串超出了maxJsonLength的限制。并得知这个属性是由JavaScriptSerializer提供的,因为MVC内置的JsonResult是用JavaScriptSerializer进行序列化的。

单纯在web.config中加入下列配置节无效:

代码语言:javascript
复制
<system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="20971520"/>
           </webServices>
       </scripting>
</system.web.extensions>

还必须重写JsonResult这个类:

代码语言:javascript
复制
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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档