• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 752
  • Last Modified:

Can I capture a more meaningful response from a web response in .NET?

If I go into fiddler, I can see this nice message,
<?xml version="1.0"?>
<response>
    <error_message ident="card_number rejected: the credit card number was entered incorrectly; the check digit does not match

But the .NET try catch just reports this anemic message,
The remote server returned an error: (500) Internal Server Error."&#9;
 System.Net.HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
0
wilfordrocks
Asked:
wilfordrocks
1 Solution
 
Craig WagnerSoftware ArchitectCommented:
Normally to get the body of the response you'd do this:

string serviceResponse = String.Empty;

using( WebResponseBase webResponse = webRequest.GetResponse() )
{
    using( StreamReader reader = new StreamReader( webResponse.GetResponseStream() ) )
    {
        serviceResponse = reader.ReadToEnd();
    }
}

Open in new window


However, I'm a little confused by what you're getting. The 500 error usually would indicate that the server threw some sort of fault/exception, but in this case you seem to be getting a 500 response and a response body. If that's the case you may need to break up the above code so you get the response stream and read it in your catch block.
0
 
Ted BouskillSenior Software DeveloperCommented:
If you want a better way to see the communication during a web transaction use the Charles Web Proxy.  http://www.charlesproxy.com/

It will do a better job of isolating the HTTP traffic.

However, if you are getting 500 errors did you know that Windows actually stores those in this folder?
C:\Windows\System32\LogFiles\HTTPERR

Many people don't look there for details about 500 errors.
0
 
jagssiduralaCommented:
Try this

If a WebException is thrown because of a protocol error, its Response
property will give you access to actual response received from the web
server. Just make sure you check the Status property accordingly:

try {
// Do WebRequest
}
catch (WebException ex) {
if (ex.Status == WebExceptionStatus.ProtocolError) {
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null) {
// Process response
}
}
}
0
 
wilfordrocksAuthor Commented:
Very helpful.  Thank you
0

Featured Post

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now