首页 > 解决方案 > 如何使用邮递员发出 POST 请求?

问题描述

我有两个模型,服务器和更新。这两个类之间的关系是 1...*N,这意味着每个 Server 有多个更新。这是我的服务器模型:

public class Server
    {
        public Server()
        {
            UpdateList = new HashSet<Update>();

        }
        [Key]
        [Required]
        public int ID { get; set; }
        [Required]
        public string ComputerName { get; set; }
        [Required]
        public string Type { get; set; }

        [Required]
        public string Estado { get; set; }

        [Required]
        public string Phase { get; set; }

        public virtual ICollection<Update> UpdateList { get; set; }
    }

这是我的更新模型:

public class Update
    {
        [Required]
        public int ID { get; set; }

        public string updateId { get; set; }

        public string updateTitle { get; set; }

        public string updateDescription { get; set; }

        [System.ComponentModel.DataAnnotations.Schema.ForeignKey("Server")]
        [Display(Name = "Server")]
        public int? ServerFK { get; set; }
        public virtual Server Server { get; set; }
    }

这是我在邮递员中使用的 POST 请求:

{
    "computerName":"ServerTestUpdate",
    "type":"ServidorAplicacional",
    "estado":"Reboot Pending",
    "phase":"0",
    "updateList":
        [{   
            
            "updateId":"idTest",
            "updateTitle":"Update1",
            "updateDescription":"TestDescription"
          
        }]
     

    }

但是,当我这样做时,我收到以下错误:

System.Text.Json.JsonException:检测到可能的对象循环。这可能是由于循环或对象深度大于允许的最大深度 32。考虑在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 以支持循环。

语法有问题还是控制器中有问题?

先感谢您

标签: jsonasp.net-coreasp.net-mvc-4postpostman

解决方案


这很可能是序列化对象的问题,因为反序列化不会关心周期。这可能是因为您的Server对象有一个Updates 集合,所有这些集合都有一个Server指向返回的属性,这会导致一个循环。

如果您将JsonIgnore属性添加到属性,这应该会消失(来自System.Text.Json.Serialization命名空间)

[JsonIgnore]
public virtual Server Server { get; set; }

推荐阅读