JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company.Sliders.Company
I get an error in response, because objects contain references to each other.
Is there a way to load data without a cycled relationship?
I use these ways but do not work:
builder.Services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
or
builder.Services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
or
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>
(options => options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
or
builder.Services.AddControllers().AddNewtonsoftJson(x =>
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
I solved my problem in.net core 6. Add this code to Program.cs.
builder.Services.AddMvc().AddJsonOption(x=>x.JsonSerializerOptions.ReferenceHanr= ReferenceHandler.Preserve);
And then add [JsonIgnore] arrtibute from System.Text.Json namespace to my model.
Public class Company{
public string CompanyName { get; set; }
[JsonIgnore]
public virtual ICollection<PageContent> PageContents { get; set; }
}
Public class Product{
public int Type { get; set; }
[JsonIgnore]
public virtual Company Company { get; set; }
}