Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling JSON circular reference exception in ASP.NET 5

So I'm playing around with Web API in ASP.NET 5. At some point my app stopped working, only showing "Bad Gateway" IIS error page (I run it in IIS Express, by F5). It took me a while to figure out what the problem was - I introduced a circular reference into a class one of my Web API methods returns, like this:

public class CircularParent
{
    public CircularChild Data;

    public CircularParent()
    {
        Data = new CircularChild(this);
    }
}

public class CircularChild
{
    public CircularParent Owner { get; set; }

    public CircularChild(CircularParent owner)
    {
        Owner = owner;
    }
}

The result is JsonSerializationException. My question is not how to solve it, but rather how to deal with such a situation in future. How can I handle such an exception? Or at least how to log it or just see it logged somewhere? UseDeveloperExceptionPage() does not help. UseExceptionHandler(errorApp => errorApp.Run(...)) does not help either, the execution doesn't get into errorApp.Run(). The debugger does not break at the exception. All I get with IIS is that rather uninformative "Bad Gateway" page.

like image 476
Dmitry Avatar asked Dec 05 '22 01:12

Dmitry


1 Answers

Try to add Newtonsoft.Json in the latest version 8.0.1-beta3 to dependencies in package.json and to use use

services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling =
            Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

See the issue for more details.

like image 163
Oleg Avatar answered Jan 01 '23 12:01

Oleg