Link to home
Start Free TrialLog in
Avatar of wilfordrocks
wilfordrocks

asked on

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();
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

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.
ASKER CERTIFIED SOLUTION
Avatar of Ted Bouskill
Ted Bouskill
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
}
}
}
Avatar of wilfordrocks
wilfordrocks

ASKER

Very helpful.  Thank you