【问题标题】:contains cycles and cannot be serialized if reference tracking is disabled, json.net and webapi包含循环,如果禁用引用跟踪,则无法序列化,json.net 和 webapi
【发布时间】:2012-11-08 23:11:24
【问题描述】:

我收到了错误:

 Object graph for type 'System.Collections.Generic.List`1[[Proj.Model.Prom, Proj.Model, 
 Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' contains cycles and cannot be 
 serialized if reference tracking is disabled.

阅读,似乎是序列化程序,但 Json.Net 声称是解决方案,我已经阅读了 WebApi 和 Framework 4.5 默认情况下有它。那么它是默认出现的吗?如果是这样,为什么我仍然收到该错误?

谢谢!吉列尔莫。

编辑:添加代码

using System;
using System.Collections.Generic;
using System.Data.Spatial;

namespace Proj.Model
{
    public class Prom
    {
        public Prom()
        {
            this.Stores = new List<Store>();
            this.Branches = new List<Branch>();
            this.Products = new List<Product>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public DbGeography Location { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public int StateId { get; set; }
        public int CategoryId { get; set; }

        public virtual ICollection<Store> Stores { get; set; }
        public virtual ICollection<Branch> Branches { get; set; }
        public virtual ICollection<Product> Products { get; set; }

        public virtual Category Category { get; set; }
        public virtual State  State  { get; set; }

    }
}

using System;
using System.Collections.Generic;

namespace Proj.Model
{
    public class Category
    {
        public Category()
        {
            this.Proms = new List<Prom>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Prom> Proms { get; set; }
    }
}

然后运行这样的东西会返回错误

public IEnumerable<Category> GetList(int estadoId, string idTiposTarjetasList)
{
    var ids = "1,2,3,4".Split(',');
    var intIds = ids.Select(int.Parse);

    var Categories = Uow.Categorias.GetAllIncluding(c => c.Proms).ToList();
    foreach (var category in Categories)
    {
        var proms = category.Proms.Where(p => intIds.Contains(p.Id) && p.StateId == stateId).ToList();
        category.Proms = proms;
    }
    return Categories
}

【问题讨论】:

标签: c# entity-framework ef-code-first asp.net-web-api entity-framework-5


【解决方案1】:

默认情况下,WebApi 将“PreserveReferencesHandling”设置为无。

您可以在 WebApiConfig.cs 中配置 Json.NET SerializerSettings:

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

【讨论】:

  • 你能分享你的 Proj.Model.Prom 课程吗?
  • 其实我认为 Json.NET 序列化程序根本不会抛出异常。看起来这是由 DataContractJsonSerializer/DataContractSerializer 抛出的。您能否检查一下 (1) 您的 WebAPI 是否使用 Json.NET(即 config.Formatters.JsonFormatter.UseDataContractJsonSerializer 未明确设置为 true)和 (2) 您的客户端代码是否在请求 JSON。
  • Maggie,你让我大开眼界,非常感谢!我很确定我已经删除了 xml 格式化程序,但是由于当时我在多个项目中工作,所以我似乎是为其他项目做的。查看浏览器请求 xml 的标头,使用 Fiddler 我将标头更改为请求 json,现在它可以工作了。顺便说一句,为什么它不能用 XML 做到这一点?有解决方法吗?谢谢!!!最好的问候。吉列尔莫。
  • 顺便说一句,代码行:config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;是必须的,没有它就行不通。它说“'ObjectContent`1'类型无法序列化内容类型'application / json; charset = utf-8'的响应正文。”,ExceptionType:“System.InvalidOperationException”和“检测到属性的自引用循环”类别',类型为'AmexToGo.Model.Categoria'。路径'[0].Promociones[0]'。”,ExceptionType:“Newtonsoft.Json.JsonSerializationException”,
  • @MaggieYing 有没有办法使用 fluent api 而不是属性来调整 datacontractserializer?
【解决方案2】:

以下对我有帮助:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2014-05-09
    • 2019-07-09
    • 1970-01-01
    相关资源
    最近更新 更多