4

我正在从基于 .NET 3.5 的 C# 解决方案向 Azure 服务总线队列发送 csv 文件。由于服务总线 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[]>();
}

在这里,我按预期将 contentType 设置为 byte[] 。但是当我尝试获取 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.

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

4

1 回答 1

1

XmlException:输入源的格式不正确。

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

文档中,我们可以知道使用带有二进制文件BrokeredMessage.GetBody<T>的方法将代理消息体反序列化为指定类型的对象。System.Runtime.Serialization.DataContractSerializerSystem.Xml.XmlDictionaryReader

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

根据Azure 服务总线发送消息 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.创建控制台项目

2.创建发送消息的令牌

 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.增加创建队列功能

 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.增加接收队列消息功能

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.在main函数中测试

  private static QueueClient queueClient;


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

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

在此处输入图像描述

  1. 接收消息。

在此处输入图像描述

Package.config 文件

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

    <packages>
      <package id="WindowsAzure.ServiceBus" version="4.0.0" targetFramework="net452" />
    </packages>
于 2017-04-25T02:27:55.790 回答