2016-04-08 12 views
1

我一直在使用可用的IClientMessageInspector(和IDispatchMessageInspector)检查基于WCF的系统中发送的消息。C#WCF - 创建自定义消息内容

目前我试图手动添加XML到邮件,我无法设法让它工作。

现状: 到达的邮件已经像

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

我想使用自定义内容,在一个字符串结构手动更换整个身体的机构。也就是说,我在字符串中有一个正确的XML主体,我想将它放在消息的正文中。

这甚至可能吗?

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

编辑2:即,我想保持从传入邮件的原始标题和所有,而是要与目前居住在一个字符串我的自定义内容

之间

<body> </body> 
取代一切。

回答

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

+0

对,对不起。当我设法修改XML部分错误,并且仍然留下了通信留下的肥皂标签时,我感到有些悲伤。但是在意识到之后,它就像一种魅力。非常感谢! – Mattedatten