所以我玩弄在ASP.NET 5.网络API在某些时候,我的应用程序停止工作,只显示“错误的网关” IIS错误页面(我在IIS快速运行,按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得到的是相当无信息“错误的网关”页面。
尝试在最新版本Newtonsoft.Json
添加8.0.1-beta3到依赖于package.json
和使用用途
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
见the issue了解更多详情。
对于ASP.NET核心:
var mvc = services.AddMvc(options =>
{
//mvc options
});
mvc.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
对于ASP.NET 2.2的核心使用配置方法Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};
}