114
votes

I have 2 entities that are related as one to many

public class Restaurant {
   public int RestaurantId {get;set;}
   public string Name {get;set;}
   public List<Reservation> Reservations {get;set;}
   ...
}
public class Reservation{
   public int ReservationId {get;set;}
   public int RestaurantId {get;set;}
   public Restaurant Restaurant {get;set;}
}

If I try to get restaurants with reservations using my api

   var restaurants =  await _dbContext.Restaurants
                .AsNoTracking()
                .AsQueryable()
                .Include(m => m.Reservations).ToListAsync();
    .....

I receive error in response, because objects contain references to each other. There are related posts that recommend to create separate model or add NewtonsoftJson configuration

Problem is that I do not want to create separate model and 2nd suggestion didn't help. Is there any way to load data without cycled relationship ? *

System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32 maxDepth) at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken) at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()

*

15
Ask it to ignore the Restaurant property of the Reservation class.Lasse V. Karlsen
Really you shouldn't be returning your DB entities directly from your API. I'd suggest creating API-specific DTOs and mapping accordingly. Granted you said you didn't want to do that but I'd consider it general good practice to keep API and persistence internals separate.mackie
"Problem is that I do not want to create separate model". Your design is fundamentally flawed unless you do just that. An API is a contract like an interface (it's literally an application programming interface). It should not ever change, once published, and any change necessitates a new version, which will need to run concurrently with the old version (which will be deprecated and eventually removed in the future). That allows clients time to update their implementations. If you return an entity directly, you're tightly coupling your data layer.Chris Pratt
Any change to that data layer then necessitates an immediate and irreversible change to the API, breaking all clients immediately until they update their implementations. In case it's not obvious, that's a bad thing. In short: never accept or return entities from an API. You should always use DTOs.Chris Pratt
"You should always use DTOs" ... well, no, not always. If the only subscriber to your API is your SPA client application - why would I waste time writing DTOs if there is nothing to brake since the only subscriber has to be updated immediately as well. Best practices are fine, but I do not like "always".mariob

15 Answers

175
votes

I have tried your code in a new project and the second way seems to work well after installing the package Microsoft.AspNetCore.Mvc.NewtonsoftJson firstly for 3.0

services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

Try with a new project and compare the differences.

138
votes

.NET Core 3.1 Install the package Microsoft.AspNetCore.Mvc.NewtonsoftJson (from https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson/ )

Startup.cs Add service

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
47
votes

Who are still facing this issue: check if you await-ed all async methods.

15
votes

Getting the setting JSON serialisation options on startup to work is probably a preferred way as you will likely have similar cases in the future. In the meantime however you could try add data attributes to your model so it's not serialised: https://www.newtonsoft.com/json/help/html/PropertyJsonIgnore.htm

public class Reservation{ 
    public int ReservationId {get;set;} 
    public int RestaurantId {get;set;} 
    [JsonIgnore]
    public Restaurant Restaurant {get;set;} 
}
10
votes

This worked using System.Text.Json

var options = new JsonSerializerOptions()
        {
            MaxDepth = 0,
            IgnoreNullValues = true,
            IgnoreReadOnlyProperties = true
        };

Using options to serialize

objstr = JsonSerializer.Serialize(obj,options);
6
votes

I got such an error when I mistakenly returned Task<object> instead of an object in the controller method. The task leads to a loop. Check what you are returning.

6
votes

After hours of debugging, it really has a simple solution. I found this link helpful.

This error was because of:

default JSON serializer used in ASP.NET Core 3.0 and the above version.

ASP.NET Core 3.0 has removed the dependency on JSON.NET and uses it’s own JSON serializer i.e ‘System.Text.Json‘.

I was able to fix the issue adding the reference to NewtonsoftJson Nuget package,

PM> Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.2

And update the Startup.cs as below,

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

ReferenceLoopHandling is currently not supported in the System.Text.Json serializer

5
votes
public class Reservation{ 
public int ReservationId {get;set;} 
public int RestaurantId {get;set;} 
[JsonIgnore]
public Restaurant Restaurant {get;set;} 

Above worked also. But I prefer the following

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

Because first we need to add the attribute to all the models we may have the cyclic reference.

2
votes

This happens because of the 2 way relationship between your data model when it comes to be JSON serialized.

You should not return your data model diectly. Map it to a new response model then return it.

2
votes

For others who did not find other solutions working, you actually need to analyze your complete call stack, and see if any async call is not awaited where it is expected to be awaited. Which is the actual issue in problem mentioned in question.

For example, consider following method in MyAppService, which calls an async Task<int> of MyOtherService:

public async Task<int> Create(InputModel input)
{
    var id = _myOtherService.CreateAndGetIdAsync(input);
    return Created("someUri", id);
}

If CreateAndGetIdAsync method is async Task, the call to this Create method above will through the given exception as mentioned in question. This is because serialization will break as id is Task<int> but not int in reality. So one must await before returing response.

Additional Note: It's important to note one more thing here, that even thought this exception arises, it doesn't impact the db operation. i.e, in my example above, the db operation will be successful. Similarly, as mentioned in OP, the exception wasn't thrown my ORM being used, but this exception was thrown later in sequence of call stack (in one of the callers).

1
votes

I got this error from default POST method in Controller created with API Controller with actions, using entity framework.

return CreatedAtAction("GetLearningObjective", new { id = learningObjective.Id }, learningObjective);

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)

When calling HttpGet directly from Postman or browser it worked without a problem. Solved by editing Startup.cs - services.AddControllers() like this:

services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});

You could also solve it like this:

services.AddControllers(options =>
{
    options.OutputFormatters.RemoveType<SystemTextJsonOutputFormatter>();
    options.OutputFormatters.Add(new SystemTextJsonOutputFormatter(new JsonSerializerOptions(JsonSerializerDefaults.Web)
    {
        ReferenceHandler = ReferenceHandler.Preserve,
    }));
});
0
votes

I came across this issue and I was confused because I have another application running the same code, only difference was I wanted to use await this time, and in the last application I used ConfigureAwait(false).GetAwaiter().GetResult();

So by removing await and adding ConfigureAwait(false).GetAwaiter().GetResult() at the end of the Async method I was able to resolve this.

0
votes

Adding the code to the Startup class solved has solved my error that was having an include statement.

services.AddControllersWithViews()
                      .AddNewtonsoftJson(options =>
                      options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
-1
votes

I encountered this and I had to tell the app/context to ignore the parent entity on the child by adding the following to the OnModelCreating(ModelBuilder builder) method in my db context class:

builder.Entity<ChildEntity>()
    .HasOne(a => a.ParentEntity)
    .WithMany(m => m.ChildEntities);
builder.Entity<ChildEntity>().Ignore(a => a.ParentEntity);

The last line with the Ignore is what did it for me.

-1
votes

The accepted answer changes the default serializer from System.Text.Json to Newtonsoft and will solve the cycle by removing the navigation property from the serialization!

Order example:

{
   "id": "d310b004-79a2-4661-2f90-08d8d25fec03"
   "orderItems": [
      {
         "orderId": "d310b004-79a2-4661-2f90-08d8d25fec03",
         "orderItemId": "83d36eda-ba03-448c-e53c-08d8d25fec0b",
         "orderItem": {
            "id": "83d36eda-ba03-448c-e53c-08d8d25fec0b",
            "name": "My order item"
         }
         // where is the reference to the order?!
      }
   ]
}

If you don't want to change the default serializer or you need to preserve the navigation property you can configure System.Text.Json serializer to preserve the references. But be careful because it changes the output structure by providing $id, $ref and $values properties!

services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve)

Order example:

{
   "$id": "1",
   "id": "d310b004-79a2-4661-2f90-08d8d25fec03"
   "orderItems": {
      $"id": "2",
      $"values": [
         {
            $"id": "3",
            "orderId": "d310b004-79a2-4661-2f90-08d8d25fec03",
            "orderItemId": "83d36eda-ba03-448c-e53c-08d8d25fec0b",
            "orderItem": {
               "id": "83d36eda-ba03-448c-e53c-08d8d25fec0b",
               "name": "My order item"
            },
            "order": {
               "$ref": "1" // reference to the order
            }
         }
      ]
   }
}