在ASP.NET 5中处理JSON循环引用异常 [英] Handling JSON circular reference exception in ASP.NET 5

查看:590
本文介绍了在ASP.NET 5中处理JSON循环引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在ASP.NET 5中使用Web API。在某些时候我的应用程序停止工作,只显示Bad GatewayIIS错误页面(我在IIS Express中运行它,由F5)。我花了一段时间来弄清问题是什么 - 我在我的Web API方法返回的类中引入了一个循环引用,如下所示:

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;
    }
}

结果是 JsonSerializationException 。我的问题不是如何解决它,而是如何在将来处理这种情况。我怎么处理这样的例外?或者至少如何记录它或只是看到它记录在某个地方? UseDeveloperExceptionPage()没有帮助。 UseExceptionHandler(errorApp => errorApp.Run(...))也没有帮助,执行没有进入 errorApp.Run( )。调试器不会在异常处中断。我得到的所有IIS都是相当无法提供信息的Bad Gateway页面。

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.

推荐答案

尝试在最新版本 Newtonsoft.Json href =https://www.nuget.org/packages/Newtonsoft.Json/8.0.1-beta3\"rel =noreferrer> 8.0.1-beta3 到包中的依赖项.json 并使用

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;
    });

参见问题了解更多细节。

这篇关于在ASP.NET 5中处理JSON循环引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆