问题描述
我有这段代码可以将 Route
对象列表发送到我的视图(ASP.Net MVC):
I have this bit of code to send a List of Route
objects to my View (ASP.Net MVC):
public ActionResult getRouteFromPart(int partId)
{
List<Route> routes = _routeService.GetRouteByPartType(partId);
if (routes == null)
{
return this.AdvancedJsonResult(null, JsonRequestBehavior.AllowGet);
}
return this.AdvancedJsonResult(new
{
Routes = routes
}, JsonRequestBehavior.AllowGet);
}
但我的 AdvancedJsonResult
类中出现异常:
But I'm getting an exception here in my AdvancedJsonResult
class:
if (Data != null)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
string result = JsonConvert.SerializeObject(this.Data, this.Formatting, settings);
response.Write(result);
}
我已经尝试过ReferenceLoopHanding.Ignore"技巧,它可以使异常静音,但列表仍然没有传递给视图.
I've tried the "ReferenceLoopHanding.Ignore" trick which silences the exception, but the list still doesn't get passed to the view.
当我将 routes
更改为单个对象而不是列表时,代码会起作用,所以我认为代码只是不喜欢使用列表.
The code works when I change routes
to a single object instead of a list, so I think the code just doesn't like working with a list.
我是这个项目的新手,所以我不知道如何解决这个问题并让它对使用 List 感到满意...
I'm new to this project so I'm not sure how to fix this and make it happy with using a List...
这是完整的异常消息,发生在 string result = JsonConvert...
行.
Here's the full Exception message, which happens on the string result = JsonConvert...
line.
检测到类型为System.Data.Entity.DynamicProxies.PartNumber_B135A5D16403B760C3591872ED4C98A25643FD10B51246A690C2F2D977973452"的自引用循环.路径'routes[0].incomingLots[0].partNumber.partType.partNumbers'.
Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.PartNumber_B135A5D16403B760C3591872ED4C98A25643FD10B51246A690C2F2D977973452'. Path 'routes[0].incomingLots[0].partNumber.partType.partNumbers'.
推荐答案
基于 Json.net 的默认 Json 格式化程序的正确答案是将 ReferenceLoopHandling 设置为 Ignore.
Well the correct answer for the default Json formater based on Json.net is to set ReferenceLoopHandling to Ignore.
只需将此添加到 Global.asax 中的 Application_Start
中:
Just add this to the Application_Start
in Global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
这是正确的方法.它将忽略指向对象的引用.
This is the correct way. It will ignore the reference pointing back to the object.
其他响应侧重于通过排除数据或通过制作外观对象来更改返回的列表,有时这不是一种选择.
Other responses focused in changing the list being returned by excluding data or by making a facade object and sometimes that is not an option.
使用 JsonIgnore 属性来限制引用可能很耗时,如果您想从另一个点开始序列化树,这将是一个问题.
Using the JsonIgnore attribute to restrict the references can be time consuming and if you want to serialize the tree starting from another point that will be a problem.
复制自此答案.
这篇关于“检测到自参考循环"JSON.Net 例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!