首先我想告訴你我的架構。 我對故事的表故事類Asp.Net Mvc Web Api Json格式化程序問題
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 /故事」我想我的故事的名單,但我把這個錯誤。我想我必須寫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:
可能重複http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop -detected-type) – CodeCaster