我有以下 WCF 服务的 XML 输入。使用 XmlReader 我正在验证消息并替换为新消息。在此过程中,xml 命名空间别名从 更改xmlns:soapenv
为xmlns:s
为了在重新创建消息时维护命名空间别名,需要在以下 C# 代码中进行哪些更改?
参考WCF 消息正文显示 <s:Body>... stream ...</s:Body> 修改后查看正确的替换消息内容。
WCF 消息对象只能“使用”一次——“使用”可以表示读取、写入或复制。消息体本质上是一个只读流,因此一旦被消费,就不能再次使用。因此,如果在检查器代码中读取消息,WCF 运行时将无法在其管道的其余部分重用该消息(即,将其编码为作为回复发送或将其解析为操作参数)。因此,如果检查器代码需要读取消息,检查器有责任重新创建消息。
输入
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header>
<To soapenv:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://local:54956/Service1.svc</To>
<Action soapenv:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService1/GetData</Action>
</soapenv:Header>
<soapenv:Body>
<tem:GetData>
<!--Optional:-->
<tem:value>4</tem:value>
</tem:GetData>
</soapenv:Body>
</soapenv:Envelope>
代码
private void MyInspectorsValidateMessageBody(ref System.ServiceModel.Channels.Message message, bool isARequest)
{
string originalMessageText = message.ToString();
if (!message.IsFault)
{
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
XmlReader bodyReader = message.GetReaderAtBodyContents().ReadSubtree();
//Settings
XmlReaderSettings wrapperSettings = new XmlReaderSettings();
wrapperSettings.CloseInput = true;
wrapperSettings.ValidationFlags = XmlSchemaValidationFlags.None;
wrapperSettings.ValidationType = ValidationType.Schema;
//Add a event handler for ValidationEventHandler of XmlReaderSettings
//Validation happens while read of xml instance
//wrapperSettings.ValidationEventHandler += new ValidationEventHandler(MyHandlerForXMLInspectionErrors);
XmlReader wrappedReader = XmlReader.Create(bodyReader, wrapperSettings);
this.isRequest = isARequest;
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;
string replacedMessageText = replacedMessage.ToString();
}
}
输出
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://local:54956/Service1.svc</To>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService1/GetData</Action>
</s:Header>
<s:Body>... stream ...</s:Body>
</s:Envelope>