2015-03-03 104 views
1

我想使用datacontractjson序列化程序向azure服務總線發送消息。我經常收到以下錯誤消息服務總線System.InvalidOperationException

未處理的異常:System.InvalidOperationException:由於其正文流已被部分使用而無法序列化消息。

這裏是我的代碼

[DataContract] 
class flow 
{ 
    [DataMember] 
    public string srcip {get; set;} 
    [DataMember] 
    public string dstip {get; set;} 
} 

主要代碼:

class Program 
    { 
     static void Main(string[] args) 
     { 
     string connectionString = "XXXXXX"; 

     MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString); 

     flow f = new flow() 
     { 
      srcip = "10.1.1.1", 
      dstip = "20.1.1.1" 
     }; 


     //Sending a message 

     MessageSender testQueueSender = factory.CreateMessageSender("XXXXX"); 

     MemoryStream stream1 = new MemoryStream(); 
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(flow)); 
     ser.WriteObject(stream1, f); 

     BrokeredMessage message = new BrokeredMessage(stream1); 

     testQueueSender.Send(message); 

     Console.WriteLine("Message(s) sent."); 





     Console.WriteLine("Done, press a key to continue..."); 

     Console.ReadKey(); 
    } 
} 

}

回答

4

它看起來好像流位置並不總是試圖發送郵件之前重置爲0。如果你嘗試這樣,它應該可靠地發送:

MessageSender testQueueSender = factory.CreateMessageSender("testpath"); 

MemoryStream stream1 = new MemoryStream(); 
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(flow)); 
ser.WriteObject(stream1, f); 

stream1.Position = 0; 

BrokeredMessage message = new BrokeredMessage(stream1); 

testQueueSender.Send(message); 
+0

當通過ServiceBus Queue Messaging發送Stream時遇到類似問題,並在將Stream.Position設置爲零時解決。謝謝。 – 2015-07-13 05:59:37