如何获取SOAP请求500错误的XML响应内容
解决SOAP调用500错误时提取Fault信息的问题
当调用SOAP接口遇到500错误时,HttpWebRequest.EndGetResponse()会抛出WebException,你可以通过捕获这个异常,从异常的Response属性中读取错误响应体,进而解析出SOAP Fault中的faultstring内容。
修改后的代码如下:
private static void CallWebService() { var url = "http://www.dneonline.com/calculator.asmx"; XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); HttpWebRequest webRequest = CreateWebRequest(url); InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); asyncResult.AsyncWaitHandle.WaitOne(); string soapResult; try { using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) { using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } Console.Write(soapResult); } } catch (WebException ex) { // 处理SOAP错误响应 using (WebResponse errorResponse = ex.Response) { if (errorResponse != null) { using (StreamReader rd = new StreamReader(errorResponse.GetResponseStream())) { string errorXml = rd.ReadToEnd(); Console.WriteLine("错误响应XML:"); Console.WriteLine(errorXml); // 解析XML提取faultstring XmlDocument doc = new XmlDocument(); doc.LoadXml(errorXml); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); nsManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); XmlNode faultStringNode = doc.SelectSingleNode("//soap:Fault/faultstring", nsManager); if (faultStringNode != null) { Console.WriteLine("\n提取的错误信息:"); Console.WriteLine(faultStringNode.InnerText); } } } } } }
关键说明:
- 捕获
WebException后,通过ex.Response获取错误响应对象,不要直接忽略异常。 - 读取错误响应流得到完整的SOAP Fault XML。
- 使用
XmlNamespaceManager处理SOAP命名空间,因为SOAP Fault的XML带有命名空间,必须指定才能正确查询节点。 - 通过XPath表达式
//soap:Fault/faultstring定位到错误信息节点,提取其文本内容。
如果你的SOAP服务使用了自定义命名空间,需要调整XmlNamespaceManager中的命名空间前缀和URI,确保与响应XML中的命名空间一致。
内容的提问来源于stack exchange,提问作者davidvera
相关产品推荐
相关产品推荐

