You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API:如何忽略子类继承的基类Id属性序列化

解决方案

EF Core 的 .Ignore(b => b.Id) 仅作用于数据库映射逻辑,不会影响 JSON 序列化行为。要在 PersonType 的 API 返回结果中忽略 Id 属性,同时不影响其他继承自 BaseObject 的类,可采用以下几种方案:

方案一:在子类中重写并标记忽略(适用于基类 Id 为可重写属性)

如果 BaseObject 的 Id 是 virtual 属性,直接在 PersonType 中重写该属性并添加 [JsonIgnore] 特性:

[PrimaryKey(nameof(PersonId), nameof(Type))]
public class PersonType : BaseObject
{
    public Guid PersonId { get; set; }
    public string Type { get; set; } = string.Empty;

    [JsonIgnore]
    public override Guid Id { get; set; }
}

这种方式仅对 PersonType 生效,其他继承 BaseObject 的类不受影响。

方案二:全局配置 JSON 序列化规则(无需修改实体类)

如果你不想修改实体代码,可以通过配置 System.Text.Json 的序列化规则,针对 PersonType 单独忽略 Id 属性:
在 Program.cs 中添加以下配置:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolverChain.Insert(0, new DefaultJsonTypeInfoResolver
        {
            Modifiers =
            {
                typeInfo =>
                {
                    if (typeInfo.Type == typeof(PersonType))
                    {
                        var idProperty = typeInfo.Properties.SingleOrDefault(p => p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase));
                        if (idProperty != null)
                        {
                            idProperty.ShouldSerialize = _ => false;
                        }
                    }
                }
            }
        });
    });

该配置会在序列化 PersonType 实例时跳过 Id 属性的输出,其他类的序列化行为保持不变。

方案三:使用 DTO 投影(推荐的 API 最佳实践)

如果你的 API 返回结果不需要直接暴露实体类,可以定义一个 PersonTypeDto,仅包含需要返回的属性,在查询时将实体映射为 DTO 返回:

public class PersonTypeDto
{
    public Guid PersonId { get; set; }
    public string Type { get; set; } = string.Empty;
    public DateTime DateUtcUpdated { get; set; }
}

查询时的映射示例:

var personTypes = await _context.PersonTypes
    .Select(pt => new PersonTypeDto
    {
        PersonId = pt.PersonId,
        Type = pt.Type,
        DateUtcUpdated = pt.DateUtcUpdated
    })
    .ToListAsync();

return Ok(new { personTypes });

这种方式完全隔离了实体与 API 返回结构,不仅解决了 Id 的问题,也符合 API 设计的单一职责原则,避免后续实体变更直接影响 API 输出。


内容的提问来源于stack exchange,提问作者sion_corn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:40:22