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

ASP.NET Core 6全局配置System.Text.Json隐藏virtual属性的方法

全局配置System.Text.Json忽略Virtual成员的实现方案

要在ASP.NET Core中全局配置System.Text.Json,让控制器自动序列化时忽略带有virtual修饰符的成员,可按以下步骤实现:

1. 自定义类型信息解析器

创建一个继承自DefaultJsonTypeInfoResolver的类,通过修改类型信息标记virtual属性为忽略状态:

public class IgnoreVirtualPropertiesResolver : DefaultJsonTypeInfoResolver
{
    protected override void ModifyTypeInfo(JsonTypeInfo typeInfo)
    {
        base.ModifyTypeInfo(typeInfo);
        if (typeInfo.Kind != JsonTypeInfoKind.Object)
            return;
        
        foreach (var property in typeInfo.Properties)
        {
            var propertyInfo = property.PropertyInfo;
            // 判断属性的Get方法是否为virtual(排除接口的抽象属性)
            if (propertyInfo != null 
                && propertyInfo.GetMethod != null 
                && propertyInfo.GetMethod.IsVirtual 
                && !propertyInfo.GetMethod.IsFinal)
            {
                property.IsIgnored = true;
            }
        }
    }
}

2. 在Program.cs中全局注册配置

在添加控制器服务时,通过AddJsonOptions指定自定义的类型解析器:

var builder = WebApplication.CreateBuilder(args);

// 添加控制器并配置Json序列化选项
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolver = new IgnoreVirtualPropertiesResolver();
    });

var app = builder.Build();

// 中间件配置...
app.MapControllers();

app.Run();

说明

  • 此配置会全局作用于所有控制器的Action返回结果,无需手动对每个接口做序列化处理。
  • 判断逻辑中排除了接口的抽象属性(这类属性的IsVirtual为true但IsFinal也为true),确保只忽略类中真正标记为virtual的成员。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:01:12