Best practices return file

Rafael Massula Almeida 61 Reputation points
2022-01-13T11:54:58.607+00:00

Hi @Anonymous / Guys
I need to return the product with the photos on the list, but I don't like the Json I got. The object is returned,164791-163320-object-errorjson.png, but I have this .NET glitch. "An unhandled exception occurred during request execution.
System.Text.Json.JsonException: A possible object loop was detected. This could be due to a cycle or if the object's depth is greater than the maximum allowable depth of 32. Consider using ReferenceHandler.Preserve in JsonSerializerOptions to support cycles. "
I assume it's the length of the Photo object's property.
I can't think of a good solution for this. Should I return bytes? Or FileStreamResult. a good idea would be different requests? Or in the same product request to include?

Developer technologies | .NET | Entity Framework Core
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. P a u l 10,766 Reputation points
    2022-01-13T13:01:47.123+00:00

    This error is thrown when you try to serialise objects to JSON which contain circular references (i.e. objects that reference objects that reference back to the original object.)

    The exception is telling you that it's climbing down your object structure, following references, and has climbed down circularly between 2 object references more than 32 times. To avoid this the serialiser can be told to assign unique IDs to the JSON, then other objects can reference using that ID, then the deserialiser will use these to avoid deserialising the same referenced object more than once. The error you're seeing above shows you how to enable this:

       Consider using ReferenceHandler.Preserve in JsonSerializerOptions to support cycles  
    

    https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-preserve-references?pivots=dotnet-6-0

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.