【问题标题】:MSMQ message cannot be parsed to objectMSMQ 消息无法解析为对象
【发布时间】:2017-02-22 22:44:37
【问题描述】:

尝试从 MSMQ 获取消息时,我得到了一些奇怪的结果 - 看起来消息已损坏。当我尝试将它解析回一个对象时,我只是得到了 xml 异常。

这就是我想要做的。

我正在使用此代码从 Web 服务写入 MSMQ

 MessageQueue queue = new MessageQueue(ConfigurationManager.AppSettings["receiptQueue"]);
            {
                queue.Formatter = new XmlMessageFormatter(new[] { typeof(Receipt) });
                Message msg = new Message();
                Receipt obj = new Receipt();
                obj.AlertId = alertId;
                obj.UserName = userName;
                obj.Version = version;
                obj.PC = pcName;
                msg.Body = obj;
                queue.Send(msg);
            }

我使用的 Receipt 对象是这样的

  public class Receipt
{
    public Receipt()
    {
    }
    public int AlertId { get; set; }
    public int Version { get; set; }
    public string UserName  { get; set; }
    public string PC { get; set; }
}

在 Windows 服务中,我试图从队列中获取对象。

初始化队列

 MessageQueue receiptQueue = new MessageQueue(ConfigurationManager.AppSettings["receiptQueue"]);
        receiptQueue.Formatter = new XmlMessageFormatter(new[] { typeof(Receipt) });
        receiptQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(ReceiptReceiver);
        receiptQueue.BeginReceive();

处理消息

 private void ReceiptReceiver(object source, ReceiveCompletedEventArgs asyncResult)
    {
        Receipt receptObj = new Receipt();
        MessageQueue mq = (MessageQueue)source;
        Message mes =mq.EndReceive(asyncResult.AsyncResult);          
        try
        {    
            receptObj = (Receipt)mes.Body; //error happens here
            //Do logic
         }
        }
        catch (Exception ex)
        {
          // ex handeling
        }
        mq.BeginReceive();
    }

我在 mq.EndReceive 之后得到以下消息信息

然后它会去捕获异常是“缺少根元素”的地方

这是来自队列的消息。它看起来格式很好。

  <?xml version="1.0"?>
<Receipt xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <AlertId>500</AlertId>
    <Version>2</Version>
    <UserName>jk9c</UserName>
    <PC>aasudv211</PC>
</Receipt>

对我做错了什么有什么建议吗?

/比尔格

【问题讨论】:

  • 您的 MSMQ 中的消息是什么?如果您手头有按摩,那么您的 MSMQ 序列化或反序列化不会出现什么问题。
  • 我从队列中添加了一条消息。它看起来格式很好

标签: c# xml-serialization msmq


【解决方案1】:

发现错误.. 这是一个非常简单且非常愚蠢的错误。 我将队列分配给了错误的格式化程序代码中的其他位置。

所以我有

 receiptQueue.Formatter = new XmlMessageFormatter(new[] { typeof(Receipt) });

 receiptQueue.Formatter = new XmlMessageFormatter(new[] { typeof(AlertMessage) });

在我删除最后一个之后一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-07
    • 2011-01-30
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多