For the sake of reuse, I have decided to make a razor component to render a list as it seemed to be the right course of action to solve the problem. Note that I am quite new to Core and have been working with the oldschool Web Applications.
Now, I have two entities that create a circular reference,
public class Address {
public List<User> Users { get; set; }
}
and
public class User {
public Address Address { get; set; }
}
When I want to render the component, I do @(await Html.RenderComponentAsync<UsersListComponent>(RenderMode.ServerPrerendered, new { Users = Model.Users }))
This throws an exception:
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.
Path: $.ParameterValues.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Address.Users.Id.
System.Text.Json.ThrowHelper.ThrowJsonException_SerializerCycleDetected(int maxDepth)
So I began searching yesterday. I have spent the entire evening and this morning, banging my head against a wall I cannot see. I have tried these questions but they did nothing for me.
WebAPI : JSON ReferenceHandler.Preserve
asp .net core 6 how to update option for json serialization. Date format in Json serialization
.NET 6 - AddJsonOptions with CamelCase not working
A couple of examples of what I have tried:
builder.Services.AddControllersWithViews(options =>
{
options.OutputFormatters.RemoveType<SystemTextJsonOutputFormatter>();
options.OutputFormatters.Add(new SystemTextJsonOutputFormatter(
new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
MaxDepth = 10,
WriteIndented = true,
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals
}));
});
builder.Services.Configure<JsonSerializerOptions>(options =>
{
options.PropertyNameCaseInsensitive = true;
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.MaxDepth = 10;
options.ReferenceHandler = ReferenceHandler.Preserve;
options.WriteIndented = true;
options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals;
});
I am getting the feeling that I am barking up the wrong tree because absolutely nothing makes any difference - not even to the worse.