Fix “The Length of the String Exceeds MaxJsonLength” in ASP.NET MVC 5

Quick fix. If a small result succeeds and a large result fails inside MVC’s JSON serializer, reduce the response size first. Project the fields a screen needs and page the query before materializing it.

This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).

Determine which limit was reached

This guide covers System.Web.Mvc.JsonResult with the .NET Framework serializer. The exception happens while writing JSON, so a controller breakpoint may show a valid result just before the request fails. Compare a small request to a large one and check whether the stack mentions JavaScriptSerializer. An IIS request-size error concerns incoming data and is a different failure.

Page the query and bound the response

This example returns up to 50 public catalog items and one look-ahead row to indicate whether another page exists. Sorting by a unique ID makes the order deterministic. If records change rapidly or users browse deep pages, use a cursor based on the last ID instead of offset pagination.

[HttpGet]
public ActionResult Catalog(int page = 1)
{
    const int pageSize = 50;
    if (page < 1 || page > 10000)
        return new HttpStatusCodeResult(400, "Page is out of range.");

    var window = db.Products
        .Where(p => p.IsPublished)
        .OrderBy(p => p.Id)
        .Skip((page - 1) * pageSize)
        .Take(pageSize + 1)
        .Select(p => new { p.Id, p.Name, p.Price })
        .ToList();

    return Json(new
    {
        items = window.Take(pageSize).ToList(),
        hasMore = window.Count > pageSize
    }, JsonRequestBehavior.AllowGet);
}

Use a measured per-action limit when necessary

If a bounded response genuinely needs more room, set MaxJsonLength on the MVC JsonResult returned by that action. The value is a character count. Choose it from representative payloads and memory measurements, rather than using int.MaxValue globally. An AJAX web-service setting under system.web.extensions does not configure the serializer that a standard MVC JsonResult creates.

Check boundary cases

Test pages with 49, 50, and 51 matching rows. Check the last page and invalid page values. Monitor response size and elapsed time with real data. A bulk export may belong in a separate download workflow with its own access and resource limits.

Related reading

Comments