Azure 服务总线 BrokeredMessage GetBody 方法在读取通过 Rest 发送的数据时抛出 SerializationException API

Azure Service Bus BrokeredMessage GetBody method throws SerializationException when reading data sent through Rest API

我正在从基于 .NET 3.5 的 C# 解决方案向 Azure 服务总线队列发送一个 csv 文件。由于 Service Bus nuget 包在 .NET 3.5 中不可用,我正在使用 Rest API.

byte[] file = File.ReadAllBytes(@"VehicleContacts.csv");

string url = baseAddress + queueName + "/messages" + "?timeout=60&api-version=2013-08 ";

WebClient webClient = new WebClient();

webClient.Proxy = proxy;
webClient.Headers[HttpRequestHeader.Authorization] = token;

// Add Broker Properties
webClient.Headers.Add("BrokerProperties", "{ \"Label\":\"VehicleContactsSync\" }");

// Add Custom Properties 
webClient.Headers.Add("FileName", "VehicleContactsSyncFile");

webClient.UploadData(url, "POST", file);

队列正常接收文件。在接收方,我可以使用 .NET 4.5。因此,我尝试使用以下代码获取消息正文:

BrokeredMessage message = queueClient.Receive(TimeSpan.FromSeconds(5));
if (message != null)
{
    var contentType = message.ContentType;                        
    var body = message.GetBody<byte[]>();
}

这里我按预期得到了 byte[] 的 contentType。但是当我尝试获取 Body 时,出现以下错误:

System.Runtime.Serialization.SerializationException occurred
  HResult=0x8013150C
  Message=There was an error deserializing the object of type System.Byte[]. 
  The input source is not correctly formatted.
  Source=System.Runtime.Serialization
  StackTrace:
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
   at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T](XmlObjectSerializer serializer)

Inner Exception 1:
XmlException: The input source is not correctly formatted.

我做错了什么,我该如何解决?

XmlException: The input source is not correctly formatted.

根据您的描述,我们可以知道正文格式不正确。 在你的情况下,你似乎使用了 CSV 格式文件。

document我们可以知道BrokeredMessage.GetBody<T>方法通过使用System.Runtime.Serialization.DataContractSerializer和二进制[=19]将代理消息体反序列化为指定类型的对象=].

What am I doing wrong and how can I fix it?

根据Azure service bus send message API,我们知道需要使用Xml格式的消息正文。

所以请尝试将文件更改为xml格式,然后就可以解决了。

编辑:

发送前请尝试DataContractSerializer您的数据

 MemoryStream ms = new MemoryStream();
 DataContractSerializer serializer = new DataContractSerializer(typeof(byte[]));
 serializer.WriteObject(ms, file);
 byte[] body = ms.ToArray();
 WebClient webClient = new WebClient { Headers = { [HttpRequestHeader.Authorization] = token } };
 // Add Broker Properties
 webClient.Headers.Add("BrokerProperties", "{ \"Label\":\"VehicleContactsSync\" }");
 // Add Custom Properties 
 webClient.Headers.Add("FileName", "VehicleContactsSyncFile");
 webClient.UploadData(queueUrl, "POST", body);

我为它做了一个演示,它在我这边工作正常。

1.Create 一个控制台项目

2.Create 发送消息的令牌

 public static string GetSasToken(string resourceUri, string keyName, string key, TimeSpan ttl)
        {
            var expiry = GetExpiry(ttl);
            string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
            HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
            return sasToken;
        }

        private static string GetExpiry(TimeSpan ttl)
        {
            TimeSpan expirySinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1) + ttl;
            return Convert.ToString((int)expirySinceEpoch.TotalSeconds);
        }

3.add 创建队列函数

 public static void CreateQueue()
        {
            var cs = "connection string";
            var queueName = "queuename";
            var namespaceManager = NamespaceManager.CreateFromConnectionString(cs);
            var messagingFactory = MessagingFactory.CreateFromConnectionString(cs);
            var ver = namespaceManager.GetVersionInfo();

            if (namespaceManager.QueueExists(queueName))
            {
                namespaceManager.DeleteQueue(queueName);
            }

            namespaceManager.CreateQueue(queueName);
}

4.add接收队列消息函数

public static void ReceiveMessage()
        {
            BrokeredMessage message = queueClient.Receive();
            if (message != null)
            {
                var body = message.GetBody<byte[]>(new DataContractSerializer(typeof(byte[])));
                Console.WriteLine(body);
            }
            Console.ReadKey();
        }

5。添加http功能发送消息

public static void SendHttpMessage()
        {
            byte[] file = File.ReadAllBytes(@"C:\tom\test.txt");
            string queueUrl = "https://servicebusname.servicebus.windows.net/" + "SampleQueue" + "/messages?timeout=60&api-version=2013-08";
            string token = GetSasToken(queueUrl,
                "Key name", "Key", TimeSpan.FromDays(1));
            MemoryStream ms = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(byte[]));
            serializer.WriteObject(ms, file);
            byte[] body = ms.ToArray();
            WebClient webClient = new WebClient { Headers = { [HttpRequestHeader.Authorization] = token } };
            // Add Broker Properties
            webClient.Headers.Add("BrokerProperties", "{ \"Label\":\"VehicleContactsSync\" }");
            // Add Custom Properties 
            webClient.Headers.Add("FileName", "VehicleContactsSyncFile");

            webClient.UploadData(queueUrl, "POST", body);

        }
主函数中的

6.Test

  private static QueueClient queueClient;


        static void Main(string[] args)
        {
           CreateQueue();
           SendHttpMessage();
           ReceiveMessage();
        }

7.During发送消息我用fiddler抓http请求,具体请看截图。我们可以看到发送的消息已经格式化

  1. 收到消息。

Package.config 文件

<?xml version="1.0" encoding="utf-8"?>

    <packages>
      <package id="WindowsAzure.ServiceBus" version="4.0.0" targetFramework="net452" />
    </packages>