0

I work with project asp core 5.0, I call external API to my API Controller using HTTP Client and The error

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 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

Controller.cs

public async Task<AuthDataAttributesResponseDTO> AuthenticationTest(AuthDTO input)
{

    var model = new AuthDataAttributesDTO
    {
        type = "authentication",
        attributes = input
    };

    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://X.XX.XX.XX/api/v1/oauth2/access-token", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<AuthDataAttributesResponseDTO>(apiResponse);
        }
    }
}
Fadl
  • 3
  • 3
  • You probably looking for [this](https://stackoverflow.com/questions/67488872/error-when-deserialize-json-net-core-5-jsonexception-a-possible-object-cycle). – Qing Guo Aug 23 '22 at 07:08

1 Answers1

0

If you're using System.Text.Json, you can add this code into Program.cs:

builder.Services.AddControllersWithViews().AddJsonOptions(option =>
{
    option.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

The AddControllersWithViews() can also be AddControllers() or AddMvc(), it depends which you are using.

If you're using Newtonsoft.Json:

builder.Services.AddControllersWithViews().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

If you can not find AddNewtonsoftJson(), try to add Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package.

Removable
  • 70
  • 4