سؤال

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

هل كانت مفيدة؟

المحلول

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;

    }

نصائح أخرى

When handling the exception, try something like:

if (ex.Response.ContentLength > 0) 
{
    string ResponseBody = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
    // Do whatever you want with ResponseBody
}

Similar to examples in http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.contentlength(v=vs.110).aspx)

The key point being that WebException had a Response property: http://msdn.microsoft.com/en-us/library/system.net.webexception.response(v=vs.110).aspx

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top