當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
MVC中JSON字符长度超出限制的异常处理
生活随笔
收集整理的這篇文章主要介紹了
MVC中JSON字符长度超出限制的异常处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
異常信息如下:
使用?JSON?JavaScriptSerializer?進(jìn)行序列化或反序列化時(shí)出錯(cuò)。字符串的長度超過了為?maxJsonLength?屬性設(shè)置的值。 這個(gè)異常是在執(zhí)行MVC中的JsonResult的時(shí)拋出的,根據(jù)異常的Message得知是序列化的字符串超出了maxJsonLength的限制。并得知這個(gè)屬性是由JavaScriptSerializer提供的,因?yàn)镸VC內(nèi)置的JsonResult是用JavaScriptSerializer進(jìn)行序列化的。 單純在web.config中加入下列配置節(jié)無效: <system.web.extensions><scripting><webServices><jsonSerialization maxJsonLength="20971520"/></webServices></scripting> </system.web.extensions>?
還必須重寫JsonResult這個(gè)類:
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
轉(zhuǎn)載于:https://www.cnblogs.com/sherlock99/p/3659759.html
總結(jié)
以上是生活随笔為你收集整理的MVC中JSON字符长度超出限制的异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse中设置svn的commit
- 下一篇: gradle idea java ssm