向MSMQ发送消息的问题

时间:2014-10-07 16:03:00

标签: c# msmq

我有一个场景,我必须以消息头+有效负载的格式向下面的msmq发送消息。以下是示例。

        Person Message
        <? Xml version="1.0"?>
        <Person>
        <Employee>
         <Name>Manthan</name>
        </employee>
        </Person>

如何将上述消息发送到msmq,我已经尝试了所有可能的解决方案,但仍然没有成功。任何帮助将不胜感激。提前致谢

以下是代码

       StringBuilder sb = new StringBuilder();
       sb.Append("Person Message"); 
       sb.Append("<?XML Version=\"1.0\">");
       sb.Append("<Person>");
       sb.Append("<Employee>");
       sb.Append("<Name>Manthan</Name>");
       sb.Append("</Employee>");
       sb.Append("</Person>");

      MessageQueue  msMq = new MessageQueue(MQPath);
      msmq.Send(sb.tostring());

MSMQ中的输出

        <?xml version="1.0"?>
         <string>Person Message&lt;?XML       Version="1.0"&gt;&lt;Person&gt;&lt;Employee&gt;&lt;Name&gt;Manthan&lt;/Name&gt;&lt;/Employee&gt;&lt;/Person&gt;</string>

以上消息与预期输出的方式不同,如何获得预期的输出

2 个答案:

答案 0 :(得分:1)

MSMQ将消息放入SOAP中,您必须反序列化结果 ....

MessageQueue  msMq = new MessageQueue(MQPath);
msmq.Send(sb.tostring());

Message[] msgs = msMq.GetAllMessages();

foreach (var msg in msgs)
      {
            System.IO.StreamReader reader = new System.IO.StreamReader(msg.BodyStream);
            MSGtext = reader.ReadToEnd();

            string MSGValue = (string)XmlDeserializeFromString(MSGtext);

        }
 }
 public object XmlDeserializeFromString(string objectData)
    {
        var serializer = new XmlSerializer(typeof(string));
        object result;

        using (TextReader reader = new StringReader(objectData))
        {
            result = serializer.Deserialize(reader);
        }
        return result;
    }

答案 1 :(得分:0)

您将不得不创建自定义消息格式化程序

        StringBuilder sb = new StringBuilder();
         sb.Append("Person Message");
         sb.Append("<?XML Version=\"1.0\">");
         sb.Append("<Person>");
         sb.Append("<Employee>");
         sb.Append("<Name>Manthan</Name>");
         sb.Append("</Employee>");
         sb.Append("</Person>");

         //write to Queue
         msMq.Formatter = new ActiveXMessageFormatter();
         msMq.Send(sb.ToString());

         //read From Queue
         MessageQueue  msMqReader = new MessageQueue(MQPath);
         msMqReader.Formatter = new ActiveXMessageFormatter();         

         Message msg = msMqReader.Receive();
         Console.WriteLine(msg.Body);

}