我看到其他人在尝试将具有导航属性的实体序列化到其他实体的集合(如父子关系(时也会遇到此错误。
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
我已经尝试将这些选项添加到WebApiConfig.cs
文件中的Register
方法中,但仍然收到相同的错误。
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;
我发现最好的方法是添加
[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 内部