2011-05-22 67 views
1

從wcf消息中檢索正文時遇到了一些問題。我試圖實現WCF消息檢查器來驗證消息對XSD架構。從WCF消息獲取正文

SOAP體看起來像以下:

<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Header xmlns="http://www.test1.com"> 
     <applicationID>1234</applicationID> 
    </Header> 
    <GetMatchRequest xmlns="http://www.tempuri.org">test</GetMatchRequest> 
    </s:Body> 

問題是,當我試圖讓身體只得到部分機構留言。僅獲取頭元素,忽略GetMatchRequest元素(可能是因爲多個命名空間的...)

我使用下面進入正文:

XmlDocument bodyDoc = new XmlDocument(); 
bodyDoc.Load(message.GetReaderAtBodyContents().ReadSubtree()); 

我也曾嘗試以下操作:

bodyDoc.Load(message.GetReaderAtBodyContents()); 

上面的代碼導致錯誤 - 這個文檔已經有一個'DocumentElement'節點。

任何人都可以請求從WCF消息中提取正文的幫助嗎?

感謝

+0

請告訴我們您的服務合約是什麼樣的。一般來說,你不需要擔心SOAP通過網絡。 WCF將這些內容抽象出來,以便您可以處理對象調用等。 – 2011-05-22 22:32:12

+0

爲什麼你覺得你需要驗證XML?如果將無效的XML發送到您的服務中,您認爲會發生什麼?你認爲什麼樣的代碼會向你發送無效的XML,如果你告訴它該XML無效,你認爲這些代碼會做什麼? – 2011-05-22 23:34:11

回答

6

Message.GetReaderAtBodyContents返回的元素沒有定位的閱讀器,但在它的第一個孩子。通常消息體只包含一個根元素,所以你可以直接加載它。但是在你的消息中它包含了多個根元素(Header和GetMatchRequest),所以如果你想在XmlDocument中加載整個主體,你需要提供一個包裝元素(XmlDocument只能有一個根元素)。在下面的示例中,我使用<s:Body>作爲包裝元素,但您可以使用任何您想要的東西。代碼只是讀取主體直到找到結束元素(</s:Body>)。

public class Post_a866abd2_bdc2_4d30_8bbc_2ce46df38dc4 
    { 
     public static void Test() 
     { 
      string xml = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""> 
    <s:Body xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> 
    <Header xmlns=""http://www.test1.com""> 
     <applicationID>1234</applicationID> 
    </Header> 
    <GetMatchRequest xmlns=""http://www.tempuri.org"">test</GetMatchRequest> 
    </s:Body> 
</s:Envelope>"; 
      Message message = Message.CreateMessage(XmlReader.Create(new StringReader(xml)), int.MaxValue, MessageVersion.Soap11); 
      Console.WriteLine(message); 
      XmlDocument bodyDoc = new XmlDocument(); 
      MemoryStream ms = new MemoryStream(); 
      XmlWriter w = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true }); 
      XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); 
      w.WriteStartElement("s", "Body", "http://schemas.xmlsoap.org/soap/envelope/"); 
      while (bodyReader.NodeType != XmlNodeType.EndElement && bodyReader.LocalName != "Body" && bodyReader.NamespaceURI != "http://schemas.xmlsoap.org/soap/envelope/") 
      { 
       if (bodyReader.NodeType != XmlNodeType.Whitespace) 
       { 
        w.WriteNode(bodyReader, true); 
       } 
       else 
       { 
        bodyReader.Read(); // ignore whitespace; maintain if you want 
       } 
      } 
      w.WriteEndElement(); 
      w.Flush(); 
      Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); 
      ms.Position = 0; 
      XmlDocument doc = new XmlDocument(); 
      doc.Load(ms); 
      Console.WriteLine(doc.DocumentElement.OuterXml); 
     } 
    } 
+0

謝謝卡洛斯!有效。 – user438975 2011-05-24 05:03:45