JsonFormatter ReferenceLoopHandling
JsonFormatter ReferenceLoopHandling
几天来我一直在为这个问题苦苦挣扎,到目前为止我发现的任何解决方案都没有带来任何乐趣。
该项目是使用 Entity Framework 6 和 WebAPI 2 构建的。
我已将我的 WebApiConfig 设置更改为
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
现在似乎发生了无限循环,并抛出了系统内存不足异常。
我似乎找不到正确的方法。
我也在WebAPI方法中试过了,还是一样的症状。
public async Task<IHttpActionResult> GetCustomer_Title(int id)
{
Customer_Title c = await db.Customer_Title.FindAsync(id);
if (c == null)
{
return NotFound();
}
var json = JsonConvert.SerializeObject(c, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Ok(json);
}
在我的 Customer_Title Class
public partial class Customer_Title
{
public Customer_Title()
{
Customer = new HashSet<Customer>();
}
[Key]
public int TitleID { get; set; }
[Required]
[StringLength(100)]
public string TitleDescription { get; set; }
public int InstanceID { get; set; }
[JsonIgnore]
public virtual ICollection<Customer> Customer { get; set; }
public virtual System_Instance System_Instance { get; set; }
}
[JsonIgnore] 属性似乎没有任何作用。
您应该使用 DTO 而不是 Entity framework 实体,
例如:
class PersonDTO {
public Name {get; set;}
}
var person = context.People.First();
var personDTO = new PersonDTO{
Name = person.Name
}
var json = new JavaScriptSerializer().Serialize(personDTO);
几天来我一直在为这个问题苦苦挣扎,到目前为止我发现的任何解决方案都没有带来任何乐趣。
该项目是使用 Entity Framework 6 和 WebAPI 2 构建的。 我已将我的 WebApiConfig 设置更改为
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
现在似乎发生了无限循环,并抛出了系统内存不足异常。
我似乎找不到正确的方法。
我也在WebAPI方法中试过了,还是一样的症状。
public async Task<IHttpActionResult> GetCustomer_Title(int id)
{
Customer_Title c = await db.Customer_Title.FindAsync(id);
if (c == null)
{
return NotFound();
}
var json = JsonConvert.SerializeObject(c, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Ok(json);
}
在我的 Customer_Title Class
public partial class Customer_Title
{
public Customer_Title()
{
Customer = new HashSet<Customer>();
}
[Key]
public int TitleID { get; set; }
[Required]
[StringLength(100)]
public string TitleDescription { get; set; }
public int InstanceID { get; set; }
[JsonIgnore]
public virtual ICollection<Customer> Customer { get; set; }
public virtual System_Instance System_Instance { get; set; }
}
[JsonIgnore] 属性似乎没有任何作用。
您应该使用 DTO 而不是 Entity framework 实体, 例如:
class PersonDTO {
public Name {get; set;}
}
var person = context.People.First();
var personDTO = new PersonDTO{
Name = person.Name
}
var json = new JavaScriptSerializer().Serialize(personDTO);