简体   繁体   中英

C# Circular reference. System.Text.Json.JsonException: A possible object cycle was detected .NET 5

I have created an API that is returning an object A, containing object B and object B is containing object A, see example below:

public class Person() { 
    string Name {get;set;}
    List<Schema> Schemas {get;set;}
}
public class Schema(){
    List<Person> Persons {get;set;}
}

In C# this will not be a problem, and an exception will not be catched (I've added try-catch-statements everywhere.

Problem: When I tried out the function using swagger the exception thrown to the client is 500.

The client calling the API is telling me that the it's a cors policy validation. This I know for sure that this is not the problem since it works well in other scenarios.

To view the actual problem I had to go to windows "Event Logger".

From event logger i found this:

Exception: 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. at System.Text.Json.ThrowHelper.ThrowJsonException_SerializerCycleDetected(Int32 maxDepth) at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

To solve the problem with circular reference I added the code below in the configuration (startup.cs, API):

   services.AddMvc()
                .AddJsonOptions(opt =>
                 {
                     opt.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
                 });

Documentation can be found at: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to?pivots=dotnet-5-0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM