Search code examples
c#httpwebresponse

Is there a way to extract the message from WebException?


Is there a way to extract the text that is being sent back as part of the WebException that occurs can occur with a HttpWebResponse? I can get all of the header information but there is a custom message being returned with the 400 or 401 response that I would like to get if possible. I am currently handling the exception in my test like this:

        var ex = Assert.Throws<WebException>(() =>
        {
            HttpWebResponse response = Utils.GetRawResponse(url);
        });

        Assert.Contains("401", ex.Message);

Here is how am getting the response:

public static HttpWebResponse GetRawResponse(string requestURL)
{

    HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;

    HttpWebResponse response = request.GetResponse() as HttpWebResponse;


    return response;

}

And this works, but does not have the custom message.

Top hopefully be a little more clear am am referring to the message text in the bottom of the screenshot.: enter image description here


Solution

  • With Gusmans reminder I created a method to extract the response from the WebException:

        public static string ParseExceptionRespose(WebException exception)
        {
            string responseContents;
            Stream descrption = ((HttpWebResponse)exception.Response).GetResponseStream();
    
            using (StreamReader readStream = new StreamReader(descrption))
            {
                responseContents = readStream.ReadToEnd();
            }
    
            return responseContents;
    
        }