pradeep pradeep - 11 months ago 123
C# Question

how to send/receive xml data to service bus queue using service bus REST API in C#?

I followed this link, to send xml data to service bus queue successfully using service bus RESTAPI from advance rest API client and postman.

This is the XML data I want to send to queue:


This is the C# code I wrote, to send xml data to queue. But whenever I am trying to receive the message from queue, I got the deserialization issues.

public static async void sendMessagesToQueueUsingRESTAPI( string SASToken)
var url = "https://<namespace>";
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);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.Created)
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();

catch(Exception ex)



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

Can you please tell me how to send/receive xml data to service bus queue using service bus rest API in C#?

Answer Source

In your receive code, message.GetBody<string>() does not just return string message as you expect. Instead, it is trying to deserialize your message using DataContractSerializer with a binary XmlDictionaryWriter. To read the message body as-is, you need to

using (var stream = message.GetBody<Stream>())
using (var streamReader = new StreamReader(stream, Encoding.UTF8))
    var body = streamReader.ReadToEnd();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download