Blazor WebAssembly JsonException: A possible object cycle was detected which is not supported

Viewed 784

I get this error because I have circular references defined in my object model. My question is, is there any way to resolve this using one of the following two options?

  1. Using Newtonsoft.Json and options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

  2. Using System.Text.Json and options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;

I'm not seeing a way to switch to Newtonsoft.Json in a Blazor WebAssembly application and I tried implementing option 2 in the ConfigureServices function of Startup.cs in my Server project but I still kept getting the error.

I'm just trying to find a solution that doesn't require me redefining my object model. The JsonIgnore attribute does not appear to be an option either because I assume, and it appears, that then any fields I define it on do not exist in the Json on the client which breaks my application.

Update: I found this site which looks to me like discusses exactly what I'm referring to here and how to implement the solution but I have not got it to work yet. If anyone is successfully using Blazor WebAssembly with circular references in your object model please let me know what you're doing.

https://github.com/dotnet/aspnetcore/issues/28286

3 Answers

Thank you for pointing out this error in Blazor. I found the answer in the issue you mentioned (this comment). You need to change json options also on the Client side. This works for me:

On server

services.AddControllersWithViews().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

On client

var response = await Http.GetFromJsonAsync<T>("{Address}", new JsonSerializerOptions
{
    ReferenceHandler =  System.Text.Json.Serialization.ReferenceHandler.Preserve,
    PropertyNamingPolicy = null
}); 

To the two options you mentioned there is a third option available if you use .NET 6 or above.

  1. Using System.Text.Json and options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;

Beware that ignoring cycles have issues on its own (such as data corruption) but if you were depending on it when you were using Newtonsoft.Json then you will be fine as it is basically the same behavior.

If you prefer to go with ReferenceHandler.Preserve, please share more info on what error you are getting and I can try to help you out.

One way to go about this is specify how much depth an object is allowed to have. Please see the documentation here regarding how to do this with System.Text.Json. I think this may help.

Related