diff --git a/src/MassTransit/Serialization/JsonConverters/SystemTextJsonConverterFactory.cs b/src/MassTransit/Serialization/JsonConverters/SystemTextJsonConverterFactory.cs index 721d1f16f88..6abd4e2031b 100644 --- a/src/MassTransit/Serialization/JsonConverters/SystemTextJsonConverterFactory.cs +++ b/src/MassTransit/Serialization/JsonConverters/SystemTextJsonConverterFactory.cs @@ -91,7 +91,7 @@ public override bool CanConvert(Type typeToConvert) if (_openTypeFactory.TryGetValue(typeInfo, out _)) return true; - if (typeToConvert.IsInterfaceOrConcreteClass() && MessageTypeCache.IsValidMessageType(typeToConvert) && !typeToConvert.IsValueTypeOrObject()) + if (IsConvertibleInterfaceType(typeToConvert)) return true; return false; @@ -157,7 +157,7 @@ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializer } } - if (typeToConvert.IsInterfaceOrConcreteClass() && MessageTypeCache.IsValidMessageType(typeToConvert) && !typeToConvert.IsValueTypeOrObject()) + if (IsConvertibleInterfaceType(typeToConvert)) { return (JsonConverter)Activator.CreateInstance( typeof(InterfaceJsonConverter<,>).MakeGenericType(typeToConvert, TypeMetadataCache.GetImplementationType(typeToConvert))); @@ -165,6 +165,30 @@ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializer throw new MassTransitException($"Unsupported type for json serialization {TypeCache.GetShortName(typeInfo)}"); } + + static bool IsConvertibleInterfaceType(Type typeToConvert) + { + if (!typeToConvert.IsInterfaceOrConcreteClass()) + return false; + + if (!MessageTypeCache.IsValidMessageType(typeToConvert)) + return false; + + if (typeToConvert.IsValueTypeOrObject()) + return false; + + foreach (var attribute in typeToConvert.GetCustomAttributes()) + { + switch (attribute.GetType().Name) + { + case "JsonDerivedTypeAttribute": + case "JsonPolymorphicAttribute": + return false; + } + } + + return true; + } }