我正在尝试使用datacontractjson序列化程序向azure服务总线发送消息。我经常收到以下错误消息
未处理的异常:System.InvalidOperationException:无法序列化邮件,因为它的正文流已被部分使用。
这是我的代码
[DataContract]
class flow
{
[DataMember]
public string srcip {get; set;}
[DataMember]
public string dstip {get; set;}
}
主要代码:
class Program
{
static void Main(string[] args)
{
string connectionString = "XXXXXX";
MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);
flow f = new flow()
{
srcip = "10.1.1.1",
dstip = "20.1.1.1"
};
//Sending a message
MessageSender testQueueSender = factory.CreateMessageSender("XXXXX");
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(flow));
ser.WriteObject(stream1, f);
BrokeredMessage message = new BrokeredMessage(stream1);
testQueueSender.Send(message);
Console.WriteLine("Message(s) sent.");
Console.WriteLine("Done, press a key to continue...");
Console.ReadKey();
}
}
}
答案 0 :(得分:4)
在尝试发送消息之前,看起来流位置并不总是重置为0。如果您尝试这样做,它应该可靠地发送:
MessageSender testQueueSender = factory.CreateMessageSender("testpath");
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(flow));
ser.WriteObject(stream1, f);
stream1.Position = 0;
BrokeredMessage message = new BrokeredMessage(stream1);
testQueueSender.Send(message);