我正在编写一个自定义 MessageInspector,以便能够根据 XSD 验证传入的 XML 文档。(这发生在消息反序列化之前。)
我得到一个例外
“只有当阅读器位于元素节点上时,才能调用 ReadSubtree()。”
在此行上调用 ReadSubTree() :
XmlReader bodyReader = message.GetReaderAtBodyContents().ReadSubtree();
这是该方法的代码(从http://msdn.microsoft.com/en-us/library/aa717047.aspx复制)
private void ValidateMessageBody(ref System.ServiceModel.Channels.Message message, bool isRequest)
{
if (!message.IsFault)
{
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
XmlReader bodyReader = message.GetReaderAtBodyContents().ReadSubtree();
XmlReaderSettings wrapperSettings = new XmlReaderSettings();
wrapperSettings.CloseInput = true;
wrapperSettings.Schemas = schemaSet;
wrapperSettings.ValidationFlags = XmlSchemaValidationFlags.None;
wrapperSettings.ValidationType = ValidationType.Schema;
wrapperSettings.ValidationEventHandler += new ValidationEventHandler(InspectionValidationHandler);
XmlReader wrappedReader = XmlReader.Create(bodyReader, wrapperSettings);
// pull body into a memory backed writer to validate
this.isRequest = isRequest;
MemoryStream memStream = new MemoryStream();
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateBinaryWriter(memStream);
xdw.WriteNode(wrappedReader, false);
xdw.Flush();
memStream.Position = 0;
XmlDictionaryReader xdr = XmlDictionaryReader.CreateBinaryReader(memStream, quotas);
// reconstruct the message with the validated body
Message replacedMessage = Message.CreateMessage(message.Version, null, xdr);
replacedMessage.Headers.CopyHeadersFrom(message.Headers);
replacedMessage.Properties.CopyProperties(message.Properties);
message = replacedMessage;
}
}
我正在使用 Fiddler 向我的 WCF 服务(IIS 托管)发送 POST 请求。内容类型设置为 application/xml。
我的输入 XML 如下所示:
<Envelope xmlns="myNamespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="0.52">
<Sender id="1" email="..." />
...
...
那么,可能是什么问题?文档并没有帮助我理解问题所在。我认为问题实际上出在 GetReaderAtBodyContents() 调用上。