2017-08-16 25 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); 
    } 
} 
相关问题