我一直在努力了解WCF的内部情况。我尝试创建自定义格式化程序和消息检查程序(通过一些在线链接在客户端和服务器上),但一直面临问题。 我在服务器上的operationcontract方法只是读取一个文件(其中包含“测试”文本)并返回一个文件流。然后,自定义分派格式化程序尝试将作为消息接收的流序列化。以下是服务器上自定义序列化程序方法的定义 -
public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
{
string content;
using(var reader = new StreamReader(((FileStream)result), Encoding.ASCII))
{ content = reader.ReadToEnd(); }
Message message = Message.CreateMessage(messageVersion, "http://tempuri.org/IService1/GetStreamVideoResponse", new CustomBodyWriter(content));
return message;
}
CustomBodyWriter实现为 -
class CustomBodyWriter : BodyWriter
{
string content;
public RawBodyWriter(string content)
: base(true)
{
this.content = content;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("GetStreamVideoResponse");
writer.WriteAttributeString("xmlns", "http://tempuri.org/");
writer.WriteStartElement("GetStreamVideoResult");
writer.WriteString(content);
writer.WriteEndElement();
}
}
我认为当我在CustomBodyWriter中的OnWriteBodyContents方法中编写xml时,xmldictionarywriter会覆盖包络。但是,我怎样才能正确插入响应元素..
当我挂钩到自定义Inspector只是为了打印在BeforeSendReply方法中发送的回复时,我在控制台看到以下输出(缺少结束包络元素) -
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w
3.org/2003/05/soap-envelope">
<s:Header>
<a:Action s:mustUnderstand="1">http://tempuri.org/IService1/GetStreamVideoRe
sponse</a:Action>
<ActivityId CorrelationId="0e0a6aae-91fa-4f9d-94b2-8c390cb5493d" xmlns="http
://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">e452a645-e8c5-44bf-81
06-d821522b7883</ActivityId>
<a:RelatesTo>urn:uuid:72b789cb-cc0b-48ac-b73a-434040434ce1</a:RelatesTo>
</s:Header>
<s:Body>
<GetStreamVideoResponse xmlns="http://tempuri.org/">
<GetStreamVideoResult>**testing**</GetStreamVideoResult>
</GetStreamVideoResponse>
</s:Body>
在客户端,我创建了自定义检查器,它试图通过简单地读取byte []中的消息的正文部分并在其上创建一个文件流然后返回来反序列化消息 -
public object DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters)
{
var getBody = message.GetReaderAtBodyContents();
byte[] buffer = getBody.ReadContentAsBase64();
FileStream fs = new FileStream("c:\\test.txt", FileMode.OpenOrCreate);//not ideal but need for testing at present
fs.Write(buffer, 0, buffer.Length);
return fs;
}
感谢期待..