【问题标题】:How to properly return nested one-to-many data in ASP.NET CORE MVC?如何在 ASP.NET CORE MVC 中正确返回嵌套的一对多数据?
【发布时间】:2019-06-24 22:01:50
【问题描述】:

我有一个MinionLeaders 表与Minions 表具有一对多 关系。一个仆从可以领导 n 个仆从,或者如果它没有任何成员,它也可以领导自己。

问题是当我尝试获取一个包含其成员为 json 的 Minion Leaders 列表时,它返回一个杂乱无章的未完成的 json :

[
    {
        "LeaderID":"ABCD000000000001",
        "Name":"Foo",
        "Members":
            [
                {
                    "ID":"EEEE000000000001",
                    "Name":"Fubar",
                    "LeaderID":"ABCD000000000001"

另外,服务器抛出一个错误:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'minionLeader' with type 'rt5_app.Models.MinionLeaders'. Path '[0].Members[0]'.

如何正确返回数据?


下面是我从数据库MinionLeadersRepository.cs获取数据的方法:

 public async Task<IEnumerable<MinionLeaders>> ListAsync()
        {
            return await context.MinionLeaders.Include(p => p.Members)
                                              .ToListAsync();
        }

ApiController.cs

public async Task<IEnumerable<MinionLeaders>> ListAsync()
        {
            return await _minionLeaders.ListAsync();
        }

MinionLeadersModel.cs

public class MinionLeaders
    {
        [Key]
        [MinLength(16)]
        [MaxLength(16)]
        public string LeaderID { get; set; }
        
        [MinLength(16)]
        [MaxLength(16)]
        public string Name { get; set; }

        public virtual List<Minion> Members { get; set; }
    }

【问题讨论】:

    标签: c# json asp.net-core json.net asp.net-core-mvc


    【解决方案1】:

    我发现这是一个序列化程序问题。 我通过将序列化程序设置设置为忽略 Startup.cs 中的循环引用来解决它

    services.AddMvc()
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
    

    但我不确定这是真正的解决方案还是只是一种解决方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2017-07-02
      • 2021-03-16
      • 1970-01-01
      相关资源
      最近更新 更多