2014-01-14 72 views
0

我有一個自定義ClientMessageInspector,它記錄了請求但未回覆我的服務。自定義客戶端MessageInspector記錄請求但不是響應

的代碼是:

namespace MessageListener.Instrumentation 
{ 
    public class MessageInspector : IClientMessageInspector 
    { 

     private Message TraceMessage(MessageBuffer buffer) 
     { 
      // Must use a buffer rather than the original message, because the Message's body can be processed only once. 
      Message msg = buffer.CreateMessage(); 

      using (RREM_GilbaneEntities3 entities3 = new RREM_GilbaneEntities3()) 
      { 
       SOAPMessage soapMessages = new SOAPMessage 
       { 
        SOAPMessage1 = msg.ToString(), 
        created = DateTime.Now, 
        source = "Interface12", 
        sourceIP = "Interface12" 
       }; 
       entities3.SOAPMessages.Add(soapMessages); 
       entities3.SaveChanges(); 
      } 

      //Return copy of origonal message with unalterd State 
      return buffer.CreateMessage(); 
     } 

     public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) 
     { 
      reply = TraceMessage(reply.CreateBufferedCopy(int.MaxValue)); 
     } 

     public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) 
     { 
      request = TraceMessage(request.CreateBufferedCopy(int.MaxValue)); 
      return null; 
     } 
    } 
} 

什麼似乎要發生的事情是AfterRecievReply和BeforeSendRequest兩者都被調用。在我調用TraceMessage之前的AfterRecieveReply中,我可以看到整個回覆。裏面TraceMessage,當我這樣做:

// Must use a buffer rather than the original message, because the Message's body can be processed only once. 

     Message msg = buffer.CreateMessage(); 

它變成回覆到垃圾:

msg {<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap:Header /> 
    <soap:Body>... stream ...</soap:Body> 
</soap:Envelope>} 

這是怎麼回事?

回答

1

回覆不是垃圾短信 - 只是當你打電話給ToString時,它沒有顯示消息的正文。記住一條消息只能被消費一次;一旦它的身體被讀取,它就不能被再次讀取。由於很多地方(包括調試器的監視窗口)都會在對象上調用ToString,所以這種方法的實現方式是,如果它不確定是否可以多次讀取消息體,那麼它不會,這似乎是你的情況。如果你想真正寫出來的消息,請嘗試使用此代碼:

public string MessageToString(Message message) { 
    using (MemoryStream ms = new MemoryStream()) { 
     XmlWriterSettings ws = new XmlWriterSettings(); 
     ws.Encoding = new UTF8Encoding(false); 
     using (XmlWriter w = XmlWriter.Create(ms)) { 
      message.WriteMessage(w); 
      w.Flush(); 
      return ws.Encoding.GetString(ms.ToArray()); 
     } 
    } 
} 
+0

>的方式,如果它不知道肯定消息體可多次讀取執行,那麼就不會,這似乎是你的情況。>>但它適用於請求消息,只是沒有回覆消息。我不明白我如何在使用EF記錄消息的方案中實現的解決方案,就像我正在做的一樣? CreateBufferedCopy是否仍然被使用? AfterReceiveReply將如何編碼? – user2471435

+0

在您的原始代碼中,將'SOAPMessage1 = msg.ToString()'行更改爲'SOAPMessage1 = MessageToString(msg)',' – carlosfigueira

+0

謝謝!有用! – user2471435

相關問題