Compartilhar via


Retrieving SOAP Envelope from WebException

Web Services might be invoked using HttpWebRequest. If the invocation raises a service specific exception, the WebException’s Message property gives “Internal Server Error (500)”. There exists a need to parse the WebException object to retrieve the original SOAP Envelope with fault details. Here is the solution:

catch(WebException wEx)
{
string str=wEx.ToString();
if(wEx.Response == null ) //If not SOAP Exception
throw new Exception(wEx.Message);
WebResponse webResp = wEx.Response;
Stream receiveStream = webResp.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);

XmlDocument xmlResponseDoc = new XmlDocument();
xmlResponseDoc.Load(readStream);
Debug.Write(readStream.ReadToEnd());
readStream.Close();
webResp.Close();
str = xmlResponseDoc.InnerXml; //str contains the SOAP Envelope

//parse the str using LoadXml method of XmlDocument class
// …
}
catch(Exception otherException)
{
//do something else
}