2017-02-22 83 views
1

當我試圖從MSMQ獲取消息時,我得到了一些stange結果 - 它看起來像消息已損壞。當我嘗試將其解析回對象時,我只是得到了xml異常。MSMQ消息無法解析到對象

這是我想要做的。

我從Web服務使用此代碼

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); 
      } 

我使用的收據對象是看起來像這樣

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服務我試圖寫入MSMQ從隊列中獲取對象。

初始化隊列

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後消息以下信息

Message object

它然後去那裏捉例外是「根元素缺失」

這是來自隊列的消息。它看起來格式不錯。

<?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> 

對我在做什麼有什麼建議嗎?

/Birger

+0

MSMQ中的消息是什麼?如果您手邊有按摩,那麼您的MSMQ序列化或反序列化就不會出錯。 – klashar

+0

我已經從隊列中添加了一條消息。它看起來格式不錯 – Birger

回答

1

找到了錯誤..這是一個非常簡單而且非常愚蠢的錯誤。 我將隊列分配給代碼中其他位置的格式錯誤。

所以我不得不

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

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

之後我刪除的最後都運作良好。