.NET 7中如何在请求序列化时排除ICollection?
在.NET 7中排除实体属性的接口序列化
针对你的需求,有几种直接的方法可以将ArchivoTxtSri属性从接口响应的序列化结果中排除,根据你使用的序列化器不同,具体操作如下:
方法一:使用System.Text.Json(.NET 7默认序列化器)
给目标属性添加[JsonIgnore]特性,该特性来自System.Text.Json.Serialization命名空间:
using System.Text.Json.Serialization; public partial class ArchivoTxtEstado { public int IdArchivoTxtEstado { get; set; } public string? Codigo { get; set; } public string? Nombre { get; set; } public string? Descripcion { get; set; } public DateTime? FechaRegistro { get; set; } public bool? Activo { get; set; } [JsonIgnore] public virtual ICollection<ArchivoTxtSri> ArchivoTxtSri { get; set; } = new List<ArchivoTxtSri>(); }
添加后,接口返回的ArchivoTxtEstado对象在序列化时会自动忽略这个属性。
方法二:使用Newtonsoft.Json(Json.NET)
如果你的项目使用的是Newtonsoft.Json作为序列化器,同样可以使用[JsonIgnore]特性,但需要引用Newtonsoft.Json命名空间:
using Newtonsoft.Json; public partial class ArchivoTxtEstado { // 其他属性保持不变... [JsonIgnore] public virtual ICollection<ArchivoTxtSri> ArchivoTxtSri { get; set; } = new List<ArchivoTxtSri>(); }
更推荐的方案:使用DTO(数据传输对象)
从架构设计角度,不建议直接修改实体类的序列化行为,而是创建专门的DTO类来定义接口返回的字段:
public class ArchivoTxtEstadoDto { public int IdArchivoTxtEstado { get; set; } public string? Codigo { get; set; } public string? Nombre { get; set; } public string? Descripcion { get; set; } public DateTime? FechaRegistro { get; set; } public bool? Activo { get; set; } // 不包含ArchivoTxtSri属性 }
然后修改接口的返回类型:
[ProducesResponseType(typeof(IEnumerable<ArchivoTxtEstadoDto>), 200)]
这种方式可以将实体模型和接口返回模型解耦,避免后续实体类变更影响接口响应格式。
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

