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
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.
.NET Core 3.1 Install the package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Startup.cs Add service
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
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.
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.
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;}
}
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);