2017-08-16 23 views
1

我需要通過XML與WebService進行通信。該服務使用saml:Assertion來驗證連接。我可以與服務器通信,但驗證總是失敗。我搜索了幾個小時是什麼問題,因爲當我使用完全相同的參數和saml票證的soapUI時,它工作。我試圖從saml:Assertion中手動刪除任何格式,因爲它是有符號的,所以如果單字節更改,它將不再工作。如何使用XmlElement.InnerXml沒有任何格式?

這裏是我的代碼:

// Insert saml:Assertion string into soapenv:Header 
private static void InsertSAML(ref XmlDocument soapXML, ref XmlNamespaceManager nsmgr, string saml) 
{ 
    // Remove all formatting 
    saml = saml.Replace("\r", ""); 
    saml = saml.Replace("\n", ""); 
    while(saml.IndexOf(" ") > -1) 
    { 
     saml = saml.Replace(" ", " "); 
    } 
    saml = saml.Replace("> <", "><"); 
    saml = saml.Replace("\" />", "\"/>"); 

    XmlElement soapHeader = (XmlElement)soapXML.SelectSingleNode("//soapenv:Envelope/soapenv:Header/wsse:Security", nsmgr); 
    if (soapHeader == null) 
    { 
     throw new Exception("Can't find \"//soapenv:Envelope/soapenv:Header/wsse:Security\""); 
    } 

    soapHeader.InnerXml += saml; 
} 

但好像當我使用soapHeader.InnerXml += saml;它會導致某種格式。一個空格將元素沒有內部內容的結束標記之前出現:

所以,我需要補充一點:

<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> 

但在最後的XML看起來是這樣的,即使我在插入之前更換這些OCCURENCES :

<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> 

我該如何擺脫這種行爲?

+0

爲什麼你認爲它是格式化失敗?使用wireshark或fiddler等嗅探器,並將soapUI響應與您的應用程序響應進行比較。它們讓你的應用看起來像soapUI。首先比較第一個請求並修改你的c#代碼,這樣頭文件和soapUI一樣。 – jdweng

+0

它必須是格式。來自soapUI和我的C#代碼的請求具有完全相同的標題和正文,除了關閉(/>)單個標記之前的空間。 –

+0

如果標題和正文相同,你在調用格式?第一個迴應是一樣的嗎?都使用http 1.0嗎?你是否獲得了200完成狀態?如果數據完全一致,我認爲這將是一個計時問題。 http使用tcp作爲傳輸層,並且可能存在tcp斷開連接。但我不這麼認爲。這更像是您同時打開兩個連接,並且服務器不允許第二個連接。 – jdweng

回答

0

正如我所說的,問題是當我將內容追加到InnerXml時,附加字節XmlDocument添加到我的xml中。我努力刪除所有格式,這是一個很好的方向。但是,與「取消格式化」saml:Assertion部分不同,我在發送到服務之前,對整個請求體進行了非格式化。現在它起作用了。在發送請求之前,我將此方法稱爲:

// Insert XML to request body 
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) 
{ 
    using (var stringWriter = new StringWriter()) 
    using (var xmlTextWriter = XmlWriter.Create(stringWriter)) 
    using (Stream stream = webRequest.GetRequestStream()) 
    { 
     // Get XML contents as string 
     soapEnvelopeXml.WriteTo(xmlTextWriter); 
     xmlTextWriter.Flush(); 
     string str = stringWriter.GetStringBuilder().ToString(); 

     // Remove all formatting 
     str = str.Replace("\r", ""); 
     str = str.Replace("\n", ""); 
     while (str.IndexOf(" ") > -1) 
     { 
      str = str.Replace(" ", " "); 
     } 
     str = str.Replace("> <", "><"); 
     str = str.Replace("\" />", "\"/>"); 

     // Write the unbeutified text to the request stream 
     MemoryStream ms = new MemoryStream(UTF8Encoding.Default.GetBytes(str)); 
     ms.WriteTo(stream); 
    } 
} 
相關問題