.Net Core 3.0 possible object cycle was detected which is not supported

前端 未结 8 1648
我寻月下人不归
我寻月下人不归 2020-12-02 09:27

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          


        
相关标签:
8条回答
  • 2020-12-02 10:07

    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 讨论(0)
  • 2020-12-02 10:15

    .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
    );
    
    0 讨论(0)
  • 2020-12-02 10:20

    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.

    0 讨论(0)
  • 2020-12-02 10:21
    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.

    0 讨论(0)
  • 2020-12-02 10:23

    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;} 
    }
    
    0 讨论(0)
  • 2020-12-02 10:23

    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);
    
    0 讨论(0)
提交回复
热议问题