Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core 3.0 possible object cycle was detected which is not supported

I have tried your code in a new project and the second way seems to work well after installing the package Microsoft.AspNetCore.Mvc.NewtonsoftJson firstly for 3.0

services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

Try with a new project and compare the differences.


.NET Core 3.1 Install the package Microsoft.AspNetCore.Mvc.NewtonsoftJson (from https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson/ )

Startup.cs Add service

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

Who are still facing this issue: check if you await-ed all async methods.


Getting the setting JSON serialisation options on startup to work is probably a preferred way as you will likely have similar cases in the future. In the meantime however you could try add data attributes to your model so it's not serialised: https://www.newtonsoft.com/json/help/html/PropertyJsonIgnore.htm

public class Reservation{ 
    public int ReservationId {get;set;} 
    public int RestaurantId {get;set;} 
    [JsonIgnore]
    public Restaurant Restaurant {get;set;} 
}

This worked using System.Text.Json

var options = new JsonSerializerOptions()
        {
            MaxDepth = 0,
            IgnoreNullValues = true,
            IgnoreReadOnlyProperties = true
        };

Using options to serialize

objstr = JsonSerializer.Serialize(obj,options);

I got such an error when I mistakenly returned Task<object> instead of an object in the controller method. The task leads to a loop. Check what you are returning.