Problem
I'm using Blazor WASM which communicates with RESTful API built with ASP.NET Core. I need to load objects with circular references.
With default serialization settings, this produces System.Text.Json.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 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions
to support cycles.
My attempt
I've added the following lines to ConfigureServices() in my Startup.cs on the server:
services.AddControllersWithViews().AddJsonOptions(options => {
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
And modified the request on the client:
data = await Http.GetFromJsonAsync<My.Shared.DataObject[]>(
"api/GetDataObjects",
new System.Text.Json.JsonSerializerOptions() {
ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve
}
);
When I run this, the server returns reasonable response:
But the client throws System.Text.Json.JsonException when parsing the response:
Cannot parse a JSON object containing metadata properties like '$id' into an array or immutable
collection type. Type 'My.Shared.DataObject[]'.
Path: $.$id | LineNumber: 0 | BytePositionInLine: 7
Why is this happening? How to fix it?