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

MassTransit 8.0.3 RabbitMQ中ConfigureJsonSerializer替换方案

MassTransit 8.0.3 版本JSON序列化配置替换方案

MassTransit 从8.x版本开始做了序列化层的重大调整:默认序列化器从Newtonsoft.Json切换为System.Text.Json,原7.x版本基于Newtonsoft的ConfigureJsonSerializer方法已被移除,替换方案分两类场景选择即可。

基础API说明

  • 8.x版本使用RabbitMQ时默认已启用System.Text.Json作为JSON序列化器,不需要额外调用cfg.UseJsonSerializer(),直接通过cfg.ConfigureJsonSerializerOptions()即可修改序列化配置。
  • 如果需要完全兼容7.x版本的Newtonsoft.Json序列化行为,需要先单独安装MassTransit.Newtonsoft NuGet包,再调用对应Newtonsoft专属配置API。

匹配原DefaultValueHandling.Include效果的配置

原Newtonsoft配置中DefaultValueHandling.Include的核心行为是:序列化、反序列化过程中始终包含所有属性,不因为属性值是类型默认值(比如值类型0、引用类型null)就忽略该属性。两种序列化器下的对应配置如下:

场景1:使用默认System.Text.Json序列化(官方推荐)

对应配置直接将DefaultIgnoreCondition设置为JsonIgnoreCondition.Never即可,这个值本身就是System.Text.Json的默认配置,行为和原DefaultValueHandling.Include完全一致。
完整配置示例:

x.UsingRabbitMq((context, cfg) =>
{
    cfg.Host(Config.GetValue<string>("RabbitMQ:Host"), "/", h =>
    {
        h.Username(Config.GetValue<string>("RabbitMQ:Username"));
        h.Password(Config.GetValue<string>("RabbitMQ:Password"));
    });

    cfg.ConfigureJsonSerializerOptions(options => 
    {
        // 显式指定匹配原DefaultValueHandling.Include行为
        options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never;
        // 其余自定义序列化配置可在此处追加
        return options;
    });

    // 注意ConfigureEndpoints建议放在所有主机、序列化配置之后,避免配置不生效
    cfg.ConfigureEndpoints(context);
});

注意:不要误用JsonIgnoreCondition.WhenWritingDefault、JsonIgnoreCondition.WhenWritingNull两个枚举值,这两个值的行为是序列化时忽略默认值/空值,和你需要的Include效果完全相反。

场景2:换回Newtonsoft.Json序列化(兼容旧项目)

如果项目中大量依赖Newtonsoft的序列化特性、自定义转换器,迁移成本过高,可以直接换回Newtonsoft序列化器。

  1. 先安装NuGet包:执行包管理命令Install-Package MassTransit.Newtonsoft
  2. 使用专属API完成配置,写法和7.x版本基本一致:
x.UsingRabbitMq((context, cfg) =>
{
    cfg.Host(Config.GetValue<string>("RabbitMQ:Host"), "/", h =>
    {
        h.Username(Config.GetValue<string>("RabbitMQ:Username"));
        h.Password(Config.GetValue<string>("RabbitMQ:Password"));
    });

    // 启用Newtonsoft JSON序列化器
    cfg.UseNewtonsoftJsonSerializer();
    // 配置序列化规则,和7.x版本的ConfigureJsonSerializer行为完全一致
    cfg.ConfigureNewtonsoftJsonSerializer(settings => 
    {
        settings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
        return settings;
    });

    cfg.ConfigureEndpoints(context);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 20:27:27