使用IClientMessageInspector重写WCF消息

时间:2014-12-04 21:25:05

标签: c# .net xml wcf soap

我正在调用供应商Web服务,其调用模式需要在body标签中使用自定义命名空间,如下所示:

<s:Body xmlns:ddw="http://www.infinity.com/bpm/model/OmniLinkServices/DDWEBCallInput" 
        xmlns:omn="http://eclipse.org/stardust/models/generated/OmniLinkServices">

我找不到通过属性配置,绑定配置等添加此命名空间的好方法,因此我创建了IClientMessageInspector的实现,以将命名空间添加到body标记中。它有效,但随后消息正文变为:

<s:Body xmlns:ddw="http://www.infinity.com/bpm/model/OmniLinkServices/DDWEBCallInput" 
   xmlns:omn="http://eclipse.org/stardust/models/generated/OmniLinkServices">
   ... stream ...
</s:Body>

注意奇数......流...身体的内容。

这是BeforeSendRequest

IClientMessageInspector的实施
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
        //Copy old message into XPathNavigator so as first step in transforming it to (newer) XDocument for modification
        Message newMessage = null;
        MessageBuffer msgbuf = request.CreateBufferedCopy(int.MaxValue);
        XPathNavigator nav = msgbuf.CreateNavigator();

        //load the old message into message stream via XmlWriter
        MemoryStream ms = new MemoryStream();
        XmlWriter xw = XmlWriter.Create(ms);
        nav.WriteSubtree(xw);
        xw.Flush();
        xw.Close();
        ms.Position = 0;

        //load the XDocument from the XmlREader
        XDocument xDoc = XDocument.Load(XmlReader.Create(ms));
        ms.Close();

        //add the sungard namespaces to the body of the message
        var body = (from x in xDoc.Descendants() where x.Name.LocalName == "Body" select x).First();
        var ddwns = new XAttribute(XNamespace.Xmlns + "ddw", "http://www.infinity.com/bpm/model/OmniLinkServices/DDWEBCallInput");
        var omnns = new XAttribute(XNamespace.Xmlns + "omn", "http://eclipse.org/stardust/models/generated/OmniLinkServices");
        body.Add(ddwns);
        body.Add(omnns);

        //create the new message
        //write the XDoc back out to memory stream
        MemoryStream newMsg = new MemoryStream();
        xw = XmlWriter.Create(newMsg);            
        xDoc.Save(xw);
        xw.Flush();
        xw.Close();
        newMsg.Position = 0;

        //create the new message        
        XmlReader reader = XmlReader.Create(newMsg);
        newMessage = Message.CreateMessage(reader, int.MaxValue, request.Version);
        request = newMessage;
        return null;
}

在函数的最后,XDocument仍然具有有效的XML,但是当我在最后创建消息时,这似乎是问题发生的地方。

有人有任何想法吗?

1 个答案:

答案 0 :(得分:0)

看起来这只是WCF记录消息的方式。看着提琴手整个xml正在经历。我不明白为什么WCF会以这种方式记录,但无论如何。

对于遇到此问题的其他任何人,仅供参考。