Asp.Net Mvc Web Api Json Formatter问题

时间:2013-12-11 08:37:04

标签: asp.net-mvc-4 asp.net-web-api json.net jsonserializer

首先,我想告诉你我的建筑。 Tale表的故事类

public class Tale
{
    [ScaffoldColumnAttribute(false)]
    public int TaleId { get; set; }
    public string TaleName { get; set; }
    public string Content { get; set; }
    public string VoicePath { get; set; }
    public virtual ICollection<Category> Category { get; set; }   
}

我的类别表的类别类

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<Tale> Tales { get; set; }
}

就像那样ı创建我的TalesCategory表

modelBuilder.Entity<Tale>()
           .HasMany<Category>(u => u.Category)
           .WithMany(r => r.Tales)
           .Map(c => c.ToTable("TalesCategory")
                       .MapLeftKey("TaleKey")
                       .MapRightKey("CategoryKey"));

和我的TaleController:ApiController功能

public IEnumerable<Tale> GetAllTales()
    {
        return TaleService.FindAllTale();
    }

我的WebApiConfig

config.Formatters.Clear();
        config.Formatters.Add(new JsonMediaTypeFormatter());

如果我写“/ api / tales”ı想要列出我的故事但是ı采取这个错误。我想我必须编写JsonMediaFormatter并尝试一些代码,但我没有成功。我能做什么?我使用.Net Framework 4.5。

{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Tale_B48C4EAA8B3983ECA938C57C1764611B3C06FAC3348891DAC636EBEBF05EA8E2'. Path '[0].Category[0].Tales'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"   konum: Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   konum: Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   konum: 

1 个答案:

答案 0 :(得分:0)

由于EF类中的导航属性,您需要打破正在拾取的循环引用。

尝试

public IEnumerable<Tale> GetAllTales()
{
    return TaleService.FindAllTale().Select(x=> new Tale 
                    { 
                        TaleId = x.TaleId, 
                        TaleName = x.TaleName,
                        ... 
                     });
}