JSON.Net的“自检示循环检测”exception

我有一些代码将List对象发送到我的View(ASP.Net MVC):

 public ActionResult getRouteFromPart(int partId) { List routes = _routeService.GetRouteByPartType(partId); if (routes == null) { return this.AdvancedJsonResult(null, JsonRequestBehavior.AllowGet); } return this.AdvancedJsonResult(new { Routes = routes }, JsonRequestBehavior.AllowGet); } 

但我在AdvancedJsonResult类中遇到exception:

 if (Data != null) { var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; string result = JsonConvert.SerializeObject(this.Data, this.Formatting, settings); response.Write(result); } 

我已经尝试了“ReferenceLoopHanding.Ignore”技巧,它使exception静音,但列表仍未传递给视图。

当我将routes更改为单个对象而不是列表时,代码有效,所以我认为代码不喜欢使用列表。

我是这个项目的新手,所以我不知道如何解决这个问题,并对使用List感到高兴…

编辑:这是完整的exception消息,它发生在string result = JsonConvert... line上。

使用类型’System.Data.Entity.DynamicProxies.PartNumber_B135A5D16403B760C3591872ED4C98A25643FD10B51246A690C2F2D977973452’检测到自引用循环。 路径’路由[0] .incomingLots [0] .partNumber.partType.partNumbers’。

错误消息的含义是有一个自引用循环。 当您请求某些实体时,您必须设置您不希望获取所有链接实体的数据库上下文。 可以通过在DbContext类构造函数中添加两行来禁用自引用循环,如下所示:

 public YourDbContext() : base("name = YourDbContext") { //add these lines in order to avoid from "Self referencing loop detected for ..." error this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; } 

希望这可以帮助…