【问题标题】:C# WCF - Creating custom Message contentC# WCF - 创建自定义消息内容
【发布时间】:2016-04-08 09:47:56
【问题描述】:

我一直在使用可用的 IClientMessageInspector(和 IDispatchMessageInspector)检查在基于 WCF 的系统中发送的消息。

目前我正在尝试手动将 XML 添加到消息中,但无法使其正常工作。

情况: 传入消息的正文类似于

<s:Body>
    <Type xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
    ...
    </Type>
</s:Body>

我想用自定义内容替换整个正文,手动构造成一个字符串。即,我在字符串中有一个正确的 XML 正文,我想将它放在消息正文中。

这可能吗?

编辑: 为了进一步澄清这个问题:我可以以某种方式访问​​消息的“原始文本”并对其进行编辑吗?

Edit2:即我想保留原始标题和传入消息中的所有内容,但想替换

之间的所有内容
<body> </body> 

使用我当前驻留在字符串中的自定义内容。

【问题讨论】:

    标签: c# xml wcf


    【解决方案1】:

    您可以使用类似于这篇博文https://blogs.msdn.microsoft.com/kaevans/2008/01/08/modify-message-content-with-wcf/中的一种方法

    简而言之,您添加EndpointBehavior,您可以在其中添加自定义MessageInspector

    Service1Client proxy = new Service1Client();
    proxy.Endpoint.Behaviors.Add(new MyBehavior());  
    
    public class MyBehavior : IEndpointBehavior
    {
            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                MyInspector inspector = new MyInspector();
                clientRuntime.MessageInspectors.Add(inspector);
            }
    }
    
    public class MyInspector : IClientMessageInspector
    {
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            var xml = "XML of Body goes here";
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
            XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
    
            Message replacedMessage = Message.CreateMessage(reply.Version, null, xdr);
            replacedMessage.Headers.CopyHeadersFrom(reply.Headers);
            replacedMessage.Properties.CopyProperties(reply.Properties);
            reply = replacedMessage;
        }
    }
    

    编辑:添加了MemoryStream,使用来自string 值的数据启动。

    【讨论】:

    • 是的,对不起。有点悲痛,因为我设法将 XML 部分修剪错了,并且仍然有通信中留下的肥皂标签。但在意识到这一点之后,它就像一个魅力。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多