public void Serialize <T>(Stream stream, SendContext <T> context) where T : class { try { context.ContentType = RawJsonContentType; if (_options.HasFlag(RawSerializerOptions.AddTransportHeaders)) { SetRawMessageHeaders <T>(context); } using var writer = new StreamWriter(stream, JsonMessageSerializer.Encoding, 1024, true); using var jsonWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; JsonMessageSerializer.Serializer.Serialize(jsonWriter, context.Message, typeof(T)); jsonWriter.Flush(); writer.Flush(); } catch (SerializationException) { throw; } catch (Exception ex) { throw new SerializationException("Failed to serialize message", ex); } }
public override bool TryGetMessage <T>(out ConsumeContext <T> message) { lock (_messageTypes) { if (_messageTypes.TryGetValue(typeof(T), out var existing)) { message = existing as ConsumeContext <T>; return(message != null); } if (typeof(T) == typeof(JToken)) { _messageTypes[typeof(T)] = message = new MessageConsumeContext <T>(this, _messageToken as T); return(true); } var typeUrn = MessageUrn.ForTypeString <T>(); if (_options.HasFlag(RawSerializerOptions.AnyMessageType) || _supportedTypes.Length == 0 || _supportedTypes.Any(x => typeUrn.Equals(x, StringComparison.OrdinalIgnoreCase))) { try { object obj; var deserializeType = typeof(T); if (deserializeType.GetTypeInfo().IsInterface&& TypeMetadataCache <T> .IsValidMessageType) { deserializeType = TypeMetadataCache <T> .ImplementationType; } using (var jsonReader = _messageToken.CreateReader()) { obj = _deserializer.Deserialize(jsonReader, deserializeType); } _messageTypes[typeof(T)] = message = new MessageConsumeContext <T>(this, (T)obj); return(true); } catch (Exception exception) { LogContext.Warning?.Log(exception, "Failed to deserialize message type: {MessageType}", TypeMetadataCache <T> .ShortName); } } _messageTypes[typeof(T)] = message = null; return(false); } }
public void Serialize <T>(Stream stream, SendContext <T> context) where T : class { try { context.ContentType = RawXmlContentType; if (_options.HasFlag(RawSerializerOptions.AddTransportHeaders)) { SetRawMessageHeaders <T>(context); } XmlMessageSerializer.Serialize(stream, context.Message, typeof(T)); } catch (SerializationException) { throw; } catch (Exception ex) { throw new SerializationException("Failed to serialize message", ex); } }