我看到其他人在尝试将具有导航属性的实体序列化为其他实体的集合(例如父子关系)时,会添加此错误的问题。
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
我尝试将这些选项添加到Register
文件中的WebApiConfig.cs
方法,但我仍然遇到同样的错误。
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
答案 0 :(得分:0)
我发现这样做的最好方法是添加
[JsonIgnore]
实体中的属性,用于您不需要序列化的引用(我使用好友类来注释实体)。这是一个例子:
[MetadataType(typeof(MenuItemValidation))]
public partial class MenuItem
{
public class MenuItemValidation
{
public int Id { get; set; }
public int Menu_Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Url { get; set; }
[Required]
public int SortOrder { get; set; }
public bool HasIcon { get; set; }
public string IconClass { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
[JsonIgnore]
public System.DateTime CreatedOn { get; set; }
[JsonIgnore]
public System.Guid CreatedBy_Id { get; set; }
[JsonIgnore]
public System.DateTime UpdatedOn { get; set; }
[JsonIgnore]
public System.Guid UpdatedBy_Id { get; set; }
public bool IsMegaMenu { get; set; }
public virtual ICollection<MenuItem> Children { get; set; }
[JsonIgnore]
public virtual MenuItem Parent { get; set; }
[JsonIgnore]
public virtual Menu Menu { get; set; }
[JsonIgnore]
public virtual User CreatedBy { get; set; }
[JsonIgnore]
public virtual User UpdatedBy { get; set; }
[JsonIgnore]
public virtual ICollection<MenuItemsLocalization> MenuItemsLocalizations { get; set; }
}
}
我还补充说:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
在App_Start / WebApiConfig.cs
中