【问题标题】:Increase json response maxJsonLength in MVC 4在 MVC 4 中增加 json 响应 maxJsonLength
【发布时间】:2013-02-23 15:58:00
【问题描述】:

加载大型 JSON 响应表单服务器时,我在 razor 视图引擎 MVC4(.net 4.5) 应用程序中遇到以下错误

在使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了在 @Html.Raw(Json.Encode(jsondata) 的 maxJsonLength 属性上设置的值”

我已经尝试在我的 web.config 中设置 MaxJsonLength 属性:

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

在发送 JSON 响应的同时尝试在服务器端进行跟踪。

 return new JsonResult()
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior,
        MaxJsonLength = Int32.MaxValue
    };

还尝试了列出的解决方案:http://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/。但没有什么对我有用:(

有人可以建议我如何避免此错误或如何增加 Jason 响应的最大长度吗?

【问题讨论】:

  • 你试过stackoverflow.com/questions/6860053/…这里建议的解决方案吗?
  • 是的,我也厌倦了这个解决方案。但没有成功
  • I have also tired this solution 很好的弗洛伊德滑 :-)

标签: jquery ajax asp.net-mvc json


【解决方案1】:

通过在视图中使用以下代码,我以某种方式摆脱了这个错误。

@{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
}
<script type="text/javascript">
var entries = @Html.Raw(serializer.Serialize(Model.FeedEntries));    
</script>

至少对我来说,这在服务器端不起作用。

【讨论】:

  • 如果您必须在视图中序列化模型,这会有所帮助。
【解决方案2】:

我的一分钱解决方案。 b) 因为 a) 在 Mvc 4.5 AFAIK 中给出了错误消息“System.Web.Mvc.JsonResult 不包含 maxJsonLength ... 的定义”,这是唯一有效的解决方法。

我把 b) 放在我的控制器中。希望这会对某人有所帮助。

问候,SM

一)

var jsonResult = Json(list, JsonRequestBehavior.AllowGet);
jsonResult.maxJsonLength = int.MaxValue;
return jsonResult;

b)

if (Request.IsAjaxRequest())
{
   //Working solution
   var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

   return new ContentResult()
   {
      Content = serializer.Serialize(list),
      ContentType = "application/json",
   };

   //Trial 2
   //var jsonResult = Json(list, JsonRequestBehavior.AllowGet);
   //jsonResult.maxJsonLength = int.MaxValue;
   //return jsonResult;

   //Trial 1
   //return Json(list, JsonRequestBehavior.AllowGet);
} 

【讨论】:

  • 在 MVC 4 中,解决方案 a) 有效。注意 jsonResult.MaxJsonLength 中的大写“M”
【解决方案3】:

这对我有用

   return new JsonResult()
            {
                Data=jsonData,
                MaxJsonLength = 86753090,
                JsonRequestBehavior=JsonRequestBehavior.AllowGet
            };

【讨论】:

  • 尝试了许多不起作用的东西,结果成功了,不错!
猜你喜欢
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 2014-11-11
相关资源
最近更新 更多