使用来自 IClientMessageInspector 的 BeforeSendRequest 注入新的 xml

Inject new xml using BeforeSendRequest from IClientMessageInspector

我想 "inject" 使用 IClientMessageInspector 中的 BeforeSendRequest 方法自定义 XML 文本。这是我试过的代码:

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{       
    String myXML = "somexmlcontent";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(myXML);
    var ms = new MemoryStream();
    XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms);
    doc.WriteTo(writer);
    writer.Flush();
    ms.Position = 0;
    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max);
    Message newReply = Message.CreateMessage(reader, int.MaxValue, request.Version);
    request = newReply;

    return null;
}

但是 return 我确实遇到了错误 "Unrecognized message version"。

在操作之前复制消息:

MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
Message message = buffer.CreateMessage();

然后根据您的 xml 创建新消息:

request = Message.CreateMessage(reader, int.MaxValue, message.Version);

您还可以创建新的消息设置原始请求对象的版本:

Message newReply = Message.CreateMessage(reader, int.MaxValue, request.Version);
request = newReply;

希望对您有所帮助