0

I have a class like this

public class Unit
{
    public int Id { get; set; }
    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "RequiredMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
    [MaxLength(30, ErrorMessageResourceName = "MaxLengthMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
    [RegularExpression(@"[\u0020\u200C‌\u202F\u0622\u0627\u0628\u067E\u062A\u062B\u062C\u0686\u062D\u062E\u062F\u0630\u0631\u0632\u0698\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\u0641\u0642\u06A9\u06AF\u0644\u0645\u0646\u0648\u0647\u06BE\u06CC\u0643\u064A\u0626]+", ErrorMessageResourceName = "RegularExpressionMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
    public string Name { get; set; }
    public int UnitTypeId { get; set; }
    public UnitType UnitType { get; set; }
    public int? ParentUnitId { get; set; }
    public Unit ParentUnit { get; set; }
    public virtual ICollection<Unit> SubUnits { get; set; }

    public Unit()
    {
        SubUnits = new HashSet<Unit>();
    }
}

and an API controller with action

public async Task<ActionResult<IEnumerable<Unit>>> GetUnits()
{
    return await _context.Units.ToListAsync();
}

I get this error with Postman (I don't use newtonsoft json.net):

System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object's depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

Please help me fix my code. Thanks

Omer
  • 8,194
  • 13
  • 74
  • 92
Omid Ataei
  • 231
  • 2
  • 5

2 Answers2

0

when return list of DBSet from context direct without select certain members the default JSON serializer will work to serialize DBSet object with all nested levels this will generate the exception you face to solve this you can add this code to the Startup class ConfigureServices method to ignore .

services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
Kols
  • 3,641
  • 2
  • 34
  • 42
MHassan
  • 415
  • 4
  • 9
0
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions
        .ReferenceHandler = ReferenceHandler.IgnoreCycles);
}
Omer
  • 8,194
  • 13
  • 74
  • 92