0

I've got a web service that returns an http 500 with some diagnostic information in the body of the response.

I'm doing something like

Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;

try
    {
        _Response = _Request.GetResponse();
        responseStream = _Response.GetResponseStream();
    }
catch   {
    //try to view the Request.GetResponse() body here.
}

Since _Request.GetResponse() is returning an http 500 there doesn't seem to be a way to view the response body. According to HTTP 500 Response with Body? this was a known issue in Java 9 years ago. I'm wondering if there's a way to do it in .NET today.

Eric
  • 2,861
  • 6
  • 28
  • 59

1 Answers1

2

The microsoft docs give a good run down of what HttpWebRequest.GetResponse returns if it fails, you can check it out here https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.getresponse?view=netframework-4.8

In your example I believe you need to check for WebException and handle it.

Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;

try
    {
        _Response = _Request.GetResponse();
        responseStream = _Response.GetResponseStream();
    }
catch (WebException w)
{
      //here you can check the reason for the web exception
      WebResponse res = w.Response;
      using (Stream s = res.GetResponseStream())
      {
           StreamReader r= new StreamReader(s);
           string exceptionMessage = r.ReadToEnd(); //here is your error info
      }
}
catch {
    //any other exception
}
Christopher Townsend
  • 1,527
  • 1
  • 13
  • 37
  • I found this thread https://stackoverflow.com/questions/1848179/500-internal-server-error-when-using-httpwebrequest-how-can-i-get-to-the-real-e and followed the answer for that. – Eric Nov 04 '19 at 21:17