我想从我在XDocument中编写的WCF客户端捕获肥皂信封消息。因此,我编写了自己的客户消息检查器:
public class MessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var xDocument = new XDocument();
using (var stream = new MemoryStream())
{
using (var writer = XmlWriter.Create(stream))
{
request.WriteMessage(writer);
writer.Flush();
stream.Position = 0;
xDocument.Save(stream);
}
}
return request;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
}
端点行为:
public class InspectorBehavior : IEndpointBehavior
{
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new MessageInspector());
}
}
我已与客户建立联系:
client.Endpoint.Behaviors.Add(new InspectorBehavior());
我的问题是,当我发送消息时,我收到来自xDocument.Save(stream)的异常。它说:
状态为Document的令牌EndDocument将导致无效的XML文档。
(对我而言)SOAP信封看起来像有效的XML:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:8080/kestrel/AirService</Action>
<h:SessionContext xmlns="http://www.mywebsite.com/soa/common/security/SessionContext_v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:h="http://www.mywebsite.com/soa/common/security/SessionContext_v1" />
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyMessage Foo="bar" xmlns="http://www.mywebsite.com/schema/air_v46_0">
</MyMessage>
</s:Body>
</s:Envelope>
那我为什么会收到此错误,如何预防呢?