Search code examples
asp.net-coredotnet-httpclient

Http Client POST Requests with complex json value in .NET Core 5 web app


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);
        }
    }
}

Solution

  • 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.