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

如何为程序集所有类型配置源生成JSON序列化(适配AOT)

ASP.NET Core AOT下批量配置JSON源生成序列化类型

方法一:程序集级特性批量注册

在项目中添加全局特性文件(如AssemblyJsonSettings.cs),在命名空间外部添加程序集级别的JsonSerializable特性,直接指定要包含的程序集:

[assembly: JsonSerializable(typeof(MyApp.Models), AssemblyName = "MyApp.Models")]
[assembly: JsonSerializable(typeof(MyApp.Dtos), AssemblyName = "MyApp.Dtos")]

源生成器会自动处理指定程序集内的所有可序列化类型,无需逐个添加类型到JsonSerializerContext类的特性中。

方法二:T4模板自动生成特性列表

如果类型分布在特定命名空间下,可使用T4模板自动扫描类型并生成JsonSerializable属性:

  1. 在项目中添加T4模板文件(如AppJsonSerializerContext.tt)
  2. 编写模板代码扫描目标程序集/命名空间的类型,自动生成上下文类:
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Linq" #>

namespace MyApp.Serialization;

[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
<#
// 加载目标程序集
var assemblyPath = @"bin\Debug\net8.0\MyApp.Models.dll";
var assembly = Assembly.LoadFrom(assemblyPath);
// 筛选需要序列化的类型(可根据需求调整条件)
var targetTypes = assembly.GetTypes()
    .Where(t => t.Namespace?.StartsWith("MyApp.Models") == true 
                && !t.IsAbstract 
                && !t.IsGenericTypeDefinition 
                && !t.IsNestedPrivate);

foreach (var type in targetTypes)
{
#>
[JsonSerializable(typeof(<#= type.FullName #>))]
<#
}
#>
public partial class AppJsonSerializerContext : JsonSerializerContext
{
}

编译项目时,T4模板会自动生成包含所有目标类型的上下文类,无需手动维护属性列表。

方法三:拆分上下文类并组合解析器(.NET 8+)

将序列化类型按模块/命名空间拆分到多个小型JsonSerializerContext类中,再通过JsonTypeInfoResolver.Combine组合使用:

  1. 创建多个上下文类,每个负责一组类型:
// 负责Models命名空间的类型
[JsonSerializable(typeof(User))]
[JsonSerializable(typeof(Product))]
public partial class ModelsJsonSerializerContext : JsonSerializerContext { }

// 负责Dtos命名空间的类型
[JsonSerializable(typeof(UserDto))]
[JsonSerializable(typeof(ProductDto))]
public partial class DtosJsonSerializerContext : JsonSerializerContext { }
  1. 在Startup/Program.cs中组合解析器:
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolver = JsonTypeInfoResolver.Combine(
            new ModelsJsonSerializerContext(),
            new DtosJsonSerializerContext()
        );
    });

这种方式既避免了单个上下文类的特性列表过长,也便于按模块维护序列化配置。

方法四:自定义源生成器(进阶)

如果需要更灵活的类型筛选逻辑,可以编写自定义Roslyn源生成器,自动扫描指定程序集的类型并生成JsonSerializerContext类。核心步骤包括:

  • 创建.NET Standard类库作为源生成器项目
  • 实现ISourceGenerator接口,扫描目标程序集的类型
  • 生成包含所有JsonSerializable属性的上下文类代码
  • 将生成器项目作为依赖引用到Web API项目中

这种方式适合超大型项目,可完全自动化类型注册,无需手动干预。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:04:52