如何使用C#中的服务总线REST API将xml数据发送/接收到服务总线队列?

时间:2017-07-17 13:20:03

标签: c# azure azureservicebus azure-servicebus-queues

我按照this链接,使用来自提前休息的API客户端和邮递员的服务总线RESTAPI成功地将xml数据发送到服务总线队列。

这是我想要发送到队列的XML数据:

<workItem>
<date>1408566000</date>
<duration>40</duration>
<desciption>test</desciption>
</workItem>

这是我编写的C#代码,用于将xml数据发送到队列。但每当我试图从队列中接收消息时,我都会遇到反序列化问题。

   public static async void sendMessagesToQueueUsingRESTAPI( string SASToken)
    {
        try
        {
            var url = "https://<namespace>.servicebus.windows.net/queue/messages";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(envelope);
            //request.ContentType = "application/atom+xml;type=entry;charset=utf-8";
            request.ContentType = "text/xml; encoding='utf-8'";
            //request.Headers.Add("Content-Type", "application/atom+xml;type=entry;charset=utf-8");
            request.Headers.Add("Authorization", SASToken);
            //request.ContentType = "application/json";
            request.ContentLength = bytes.Length;

            request.Method = "POST";
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.Created)
            {
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
            }

        }
        catch(Exception ex)
        {

        }

        Console.ReadLine();
    }

   public static void receiveMessagesFromQueue()
    {
        //Receive messages from the queues
        var client = QueueClient.CreateFromConnectionString(nsConnectionString, queuePath);
        client.OnMessage(message =>
        {

          Console.WriteLine(String.Format("Receive Message body: {0}",    message.GetBody<string>()));
          Console.WriteLine(String.Format("Receive Message id: {0}", message.MessageId));
        });

        Console.WriteLine("Press ENTER to exit program");
        Console.ReadLine();
    }

您能否告诉我如何使用C#中的服务总线休息API将xml数据发送/接收到服务总线队列?

1 个答案:

答案 0 :(得分:2)

在您的接收代码中,string不仅会按预期返回DataContractSerializer消息。相反,它正在尝试使用带有二进制XmlDictionaryWriter的{​​{1}}来反序列化您的邮件。要按原样阅读邮件正文,您需要

using (var stream = message.GetBody<Stream>())
using (var streamReader = new StreamReader(stream, Encoding.UTF8))
{
    var body = streamReader.ReadToEnd();
}