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

如何在.NET Core 6的System.Text.Json中无特性排除Func类型属性序列化

排除所有Func类型属性的System.Text.Json序列化方案

在.NET Core 6的System.Text.Json环境下,无需添加[JsonIgnore]或其他特性,即可全局排除所有Func类型的属性,具体实现步骤如下:

1. 自定义类型信息修饰器

创建一个方法,用于修改序列化时的类型元数据,直接移除所有Func系列委托类型的属性:

private static void RemoveFuncProperties(JsonTypeInfo typeInfo)
{
    if (typeInfo.Kind != JsonTypeInfoKind.Object)
        return;

    // 倒序遍历属性列表,避免移除元素时索引错乱
    for (int i = typeInfo.Properties.Count - 1; i >= 0; i--)
    {
        var propertyType = typeInfo.Properties[i].PropertyType;
        // 判断属性类型是否为Func系列委托:检查是否继承自Delegate,且名称以Func`开头(泛型Func的命名格式为Func`1、Func`2等)
        if (propertyType.IsAssignableTo(typeof(Delegate)) && propertyType.Name.StartsWith("Func`"))
        {
            typeInfo.Properties.RemoveAt(i);
        }
    }
}

2. 配置JsonSerializerOptions

将上述修饰器注入到DefaultJsonTypeInfoResolver中,生成自定义的序列化配置:

var jsonOptions = new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers = { RemoveFuncProperties }
    }
};

使用该配置进行序列化时,所有Func类型的属性会被自动排除:

var foo = new Foo
{
    DoCalculation = () => 42,
    Bar = "Hello World"
};

// 序列化结果仅包含Bar属性:{"Bar":"Hello World"}
string serializedJson = JsonSerializer.Serialize(foo, jsonOptions);

3. ASP.NET Core全局配置

如果是在ASP.NET Core项目中,想要让所有API接口的序列化都应用该规则,可在Program.cs中全局配置:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver
        {
            Modifiers = { RemoveFuncProperties }
        };
    });

内容的提问来源于stack exchange,提问作者THX-1138

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:17:26