Can I set an unlimited length for maxJsonLength in web.config?

后端 未结 29 3185
礼貌的吻别
礼貌的吻别 2020-11-21 06:43

I am using the autocomplete feature of jQuery. When I try to retrieve the list of more then 17000 records (each won\'t have more than 10 char length), it\'s exceeding the le

29条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 07:33

    Fix for ASP.NET MVC: if you want to fix it only for particular action that is causing the problem then change this code:

    public JsonResult GetBigJson()
    {
        var someBigObject = GetBigObject();
        return Json(someBigObject);
    }
    

    to this:

    public JsonResult GetBigJson()
    {
        var someBigObject = GetBigObject();
        return new JsonResult()
        {
            Data = someBigObject,
            JsonRequestBehavior = JsonRequestBehavior.DenyGet,
            MaxJsonLength = int.MaxValue
        };
    }
    

    And the functionality should be same, you can just return bigger JSON as response.


    Explanation based on ASP.NET MVC source code: you can check what Controller.Json method does in ASP.NET MVC source code

    protected internal JsonResult Json(object data)
    {
        return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
    }
    

    It is calling other Controller.Json method:

    protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
    

    where passed contentType and contentEncoding object are null. So basically calling return Json(object) in controller is equivalent to calling return new JsonResult { Data = object, JsonRequestBehavior = sonRequestBehavior.DenyGet }. You can use second form and parameterize JsonResult.

    So what happens when you set MaxJsonLength property (by default it's null)? It's passed down to JavaScriptSerializer.MaxJsonLength property and then JavaScriptSerializer.Serialize method is called :

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    if (MaxJsonLength.HasValue)
    {
        serializer.MaxJsonLength = MaxJsonLength.Value;
    }
    
    if (RecursionLimit.HasValue)
    {
        serializer.RecursionLimit = RecursionLimit.Value;
    }
    
    response.Write(serializer.Serialize(Data));
    

    And when you don't set MaxJsonLenght property of serializer then it takes default value which is just 2MB.

提交回复
热议问题