1

我們正在使用Microsoft ServiceBus QueueClient將消息發送到服務總線。在收到消息時,我們正在使用ServiceBus REST API。身體的反序列化失敗了,我們無法找出根本原因。Microsoft Service Bus REST客戶端 - 從隊列中讀取時遇到的問題

示例代碼以如下發送消息:

MessagingFactory messagingFactory = 
    MessagingFactory.CreateFromConnectionString(....); 

Console.WriteLine("Creating Service Bus Queue Client..."); 

QueueClient queueSendClient = messagingFactory.CreateQueueClient(.); 

// Send message M1 to the topic. 
Console.WriteLine("Sending message.. "); 

BrokeredMessage bm = CreateMessage(); 
queueSendClient.Send(bm); 

的實例化的CreateMessage具有序列化對象實例的BrokeredMessage。

private static BrokeredMessage CreateMessage() 
{ 
    JObject o1 = JObject.Parse(File.ReadAllText(@"..\..\requestJson.json")); 

    string jsonMessage = JsonConvert.SerializeObject(o1); 

    CommandMessage commandMessage = new CommandMessage(); 
    JsonCommand content = new JsonCommand("abc", "def", jsonMessage); 

    List<Command> list = new List<Command>(); 
    list.Add(content); 
    commandMessage.Initialize(list, false, false); 

    var message = new BrokeredMessage(commandMessage); 

    return message; 
} 

注:對CommandMessage,JsonCommand,命令的使用[DataContract]裝飾。

如果我們使用QueueClient進行接收,那麼消息的接收工作正常。但在我們的例子中,我們正在使用Service Bus Rest Client。

接收消息代碼如下:

const string ServiceBusNamespace = "mysb2015-ns"; 
string baseAddressHttp = "https://" + ServiceBusNamespace + ".servicebus.windows.net/"; 
string queueAddress = baseAddressHttp + QueueName; 

HttpResponseMessage response = await this.httpClient.PostAsync(address + "/messages/head?timeout=60", new ByteArrayContent(new Byte[0])); 

byte[] body = response.Content.ReadAsByteArrayAsync().Result; 

DataContractSerializer deserializer = new DataContractSerializer(typeof(CommandMessage)); 
using (MemoryStream ms = new MemoryStream(body)) 
{ 
CommandMessage cmdMsg = (CommandMessage)deserializer.ReadObject(ms); 
} 

讀取對象失敗所不同的是在根級別的數據是無效的:

System.Runtime.Serialization.SerializationException了未處理 HResult = -2146233076 Message =反序列化CommandMessage類型的對象時發生錯誤。根級別的數據無效。第1行,位置1. Source = System.Runtime.Serialization

我們查看了響應中的內容類型標題,它是application/xml; utf-8。

回答

1

通過使用的DataContractSerializer與二進制 的XmlDictionaryWriter初始化從給定 對象BrokeredMessage類的新實例。

當您將BrokeredMessage發送到隊列時,XmlDictionaryWriter正在添加其類型指示。如果您使用QueueClient進行接收,則不會出現問題。因爲它可以解決這種類型的指示。但是,如果您使用的不是QueueClient,則會遇到反序列化問題。

解決方案:反序列化之前

  1. 刪除指示符。
  2. 使用BrokeredMessage的其他構造函數。 BrokeredMessage(Stream messageBodyStream, bool ownsStream)並自己控制郵件正文 。

在這種article他們解釋的問題和解決方案。

相關問題