gpt4 book ai didi

c# - 如何使用 DataContractSerializer 序列化 WCF 消息?

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:28 25 4
gpt4 key购买 nike

我正在尝试使用 DataContractSerializer 序列化 WCF 消息以获取消息大小(不使用服务跟踪查看器)。以下是代码片段:

public void BeforeSendReply(ref Message reply, object correlationState)
{
byte[] bytes = null;
var messageBuffer = reply.CreateBufferedCopy(Int32.MaxValue);
var message = messageBuffer.CreateMessage();
var dcs = new DataContractSerializer(typeof(Message));
using (var ms = new MemoryStream())
{
dcs.WriteObject(ms, message);
bytes = ms.ToArray();
Console.WriteLine(String.Format("Message size = {0}", bytes.Count()));
}
}

这样做会引发以下异常:

Type 'System.ServiceModel.Channels.BodyWriterMessage' cannot be serialized. Cons ider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the typ e is a collection, consider marking it with the CollectionDataContractAttribute.

可以做什么?

最佳答案

Message 类不是数据协定类型或 Xml 序列化程序类型。 WCF特例吧。要找到长度,您的代码应该更像这样:

    public void BeforeSendReply(ref Message reply, object correlationState)
{
var messageBuffer = reply.CreateBufferedCopy(Int32.MaxValue);
var message = messageBuffer.CreateMessage();

using (var ms = new MemoryStream())
{
var xw = XmlWriter.Create(ms);
message.WriteMessage(xw);
Console.WriteLine(String.Format("Message size = {0}", ms.Length));
}
}

关于c# - 如何使用 DataContractSerializer 序列化 WCF 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com