使用IClientMessageInspector中的BeforeSendRequest注入新的xml

时间:2016-06-21 09:11:57

标签: c# .net xml wcf iclientmessageinspector

我想使用BeforeSendRequest中的IClientMessageInspector方法“注入”自定义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;
}

但它确实给我带来了错误“无法识别的消息版本”。

1 个答案:

答案 0 :(得分:1)

在操作之前复制一条消息:

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;

希望有所帮助