Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extend the limit of RecursionLimit in C# asp.net MVC

in ASP.NET MVC i got the exception RecursionLimit exceeded when i try to sent the data to browser through JSON.

how i can make it work no matter how much big JSON is.

like image 633
Anirudha Gupta Avatar asked May 09 '11 09:05

Anirudha Gupta


4 Answers

The default value of the RecursionLimit property is 100, which means that it can serialise objects that are nested to a depth of 100 objects referencing each other.

I can't imagine that you actually have objects that are nested that deep, so the most likely reason for the error message is that you have an object that contains a reference to itself, or two objects that have references to each other. As that causes an infinite chain of child objects, you get the equivalent of a stack overflow in the serialiser.

like image 142
Guffa Avatar answered Oct 02 '22 06:10

Guffa


Use view models to break the recursion. You cannot JSON serialize objects that are recursively referencing themselves. Ayende Rahien has a nice series of blog posts about this issue.

like image 33
Darin Dimitrov Avatar answered Oct 02 '22 07:10

Darin Dimitrov


You can JSON Serialize objects that are recursively referencing themselves as you Ignore those Properties. My Users Class has a Property that also is a User Object, but I ignore that Property doing:

    Users oSuperior;
    [ScriptIgnore(), XmlIgnore()]
    public Users Superior
    {
        get
        {

            if (oSuperior == null)
            {
                oSuperior = new Users();

                if (iIDUserSuperior > 0)
                    oSuperior.Load(iIDUserSuperior);
            }
            return oSuperior;
        }
    }
like image 32
WakoAivan Avatar answered Oct 02 '22 06:10

WakoAivan


It seems that Microsoft has added some helpful properties to the JsonResult Class for increasing the recursion limit and maximum JSON length in the .NET framework 4.5:

public ActionResult GetJson()
{
    var result = Json(obj);
    result.RecursionLimit = 1024;
    result.MaxJsonLength = 8388608;
    return result;
}

Hence, now you can easily set how "big" you want to allow your JSON objects to be by setting those properties.

like image 40
Thomas C. G. de Vilhena Avatar answered Oct 02 '22 06:10

Thomas C. G. de Vilhena