c# - 处理 ASP.NET 5 中的 JSON 循环引用异常

标签 c# iis asp.net-core json.net

所以我在 ASP.NET 5 中使用 Web API。有时我的应用程序停止工作,只显示“Bad Gateway”IIS 错误页面(我在 IIS Express 中运行它,按 F5)。我花了一段时间才弄清楚问题出在哪里 - 我在我的 Web API 方法返回的类中引入了一个循环引用,如下所示:

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”页面。

最佳答案

尝试在最新版本中添加Newtonsoft.Json 8.0.1-beta3 package.json 中的依赖项并使用 use

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

参见 the issue了解更多详情。

关于c# - 处理 ASP.NET 5 中的 JSON 循环引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34420397/

相关文章:

wcf - 如何在 IIS 6.0 上部署我的 WCF 服务?

c# - 如何在 Visual Studio 中快速注入(inject)依赖项?

c# - 使用多个非嵌套文件在 Visual Studio 2012 中创建项目模板

c# - ORM 的哪些选择允许接近 'flick a switch' 在...SQL Server/SQL Azure 和 PostgreSQL/'Cloud' PostgreSQL 之间更改 RDBMS

iis - Kestrel + IIS 中的 HttpClient 调用速度缓慢

jquery - 如何防止共享主机上的 IIS 应用程序池空闲超时

c# - 不可为空的字符串类型,如何与 Asp.Net Core 选项一起使用

c# - 如何使用 FluentAssertions 在 XUnit 中测试 MediatR 处理程序

c# - 让单元测试返回 async void 不好吗?

c# - 关于 ViewModel 和 View 交互