I am trying to get a specific info from all the messages consumed by my service, and I do not want to repeat the same code inside each consumer I have.
So I created a class that implements IReceiveObserver and inside public Task PreReceive(ReceiveContext context) I am trying to get the message body, except that I could not.
public Task PreReceive(ReceiveContext context)
{
var body = context.GetBody();
return null;
}
I am assuming that body will contain the message body, so I am trying to deserialize it using:
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
object o = formatter.Deserialize(stream);
return o;
}
var Deserialized =(GeneralMessageType) DeserializeFromStream((MemoryStream)body);
I am getting the following error:
System.Runtime.Serialization.SerializationException: 'The input stream is not a valid binary format.
Is this the correct way of achieving what I need? I think I am following the right approach but I have an issue in extracting the message body.
Update:
Message body using Console.WriteLine("{0}", (new StreamReader(stream)).ReadToEnd());:
{\r\n \"messageId\": \"01110000-5d1b-0015-b7c9-08d5479e73b2\",\r\n \"correlationId\": \"da197981-a10e-43a9-a53b-67b7a3261511\",\r\n \"conversationId\": \"01110000-5d1b-0015-80d3-08d5479e73a6\",\r\n \"sourceAddress\": \"queue URL",\r\n \"destinationAddress\": \"receiverURL",\r\n \"messageType\": [\r\n \"urn:message:MessageType"\r\n ],\r\n \"message\": {\r\n \"correlationId\": \"da197981-a10e-43a9-a53b-67b7a3261511\",\r\n \"Id\": \"62d2bfff-7e20-4b51-b431-7d46e44abfc0\",\r\n \"Name\": \"'''yry'''\",\r\n \"Code\": \"ryryyy\",\r\n \"isActive\": true,\r\n \"username\": \"username\",\r\n \"password\": \"*****\",\r\n \"isUserActive\": true\r\n },\r\n \"headers\": {},\r\n \"host\": {\r\n \"machineName\": \"myMachine\",\r\n
\"processName\": \"w3wp\",\r\n \"processId\": 4568,\r\n
\"assembly\": \"MassTransit\",\r\n \"assemblyVersion\": \"3.5.7.1082\",\r\n \"frameworkVersion\": \"4.0.30319.42000\",\r\n \"massTransitVersion\": \"3.5.7.1082\",\r\n
\"operatingSystemVersion\": \"Microsoft Windows NT 10.0.16299.0\"\r\n }\r\n}"
BinaryFormatterwhen serializing, and therefore you are getting this error when you try to deserialize. - gmileyMemoryStreamlook like if you just capture it and write it out? Try outputting using:Console.WriteLine("MemoryStream Content: {0}", (new StreamReader(stream)).ReadToEnd());- gmiley