Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...