2016-04-08 16 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