I got this error:
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.
System.Text.Json.ThrowHelper.ThrowJsonException_SerializerCycleDetected
I've already added:
.AddJsonOptions(x =>
{
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
}
);
to the configuration, but this doesn't seem take effect.
The only way I can remove this error is adding the attribute [JsonIgnore]
on the navigation properties of my models
but i'm sure i'm not applying .AddJsonOptions
in the right place
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddNotyf(o =>
{
o.DurationInSeconds = 10;
o.IsDismissable = true;
o.HasRippleEffect = true;
});
services.AddApplicationLayer();
services.AddInfrastructure(_configuration);
services.AddPersistenceContexts(_configuration);
services.AddRepositories();
services.AddSharedInfrastructure(_configuration);
services.AddMultiLingualSupport();
services.AddControllersWithViews()
.AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; //<-- **** added this
);
services.AddAutoMapper(Assembly.GetExecutingAssembly());
services.AddDistributedMemoryCache();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IViewRenderService, ViewRenderService>();
}
or maybe the JSON serializer is configured correctly at controller level but the error is originated from another source?
Looking deeper in the stacktrace of the error it's generated from:
await _distributedCache.SetAsync(cacheKey, anagReparto);
where
_distributedCache
is Microsoft.Extension.Caching.Distributed.IDistributedCache
maybe this package needs a its own JSON configuration and don't use the controller's JSON serializer options that i've configured?