views:

432

answers:

5

Behold the code:

using (var client = new WebClient())
{
    try
    {
        var bytesReceived = client.UploadData("http://localhost", bytesToPost);
        var response = client.Encoding.GetString(bytesReceived);
    }
    catch (Exception ex)
    {
    }
}

I am getting this HTTP 500 internal server error when the UploadData method is called. But I can't see the error description anywhere in the "ex" object while debugging. How do I rewrite this code so I can read the error description?

A: 

Try catching a HttpException and call GetHtmlErrorMessage() on it

Gábor Hargitai
It's a WebException, it won't cast to HttpException. Believe me, I tried.
Jader Dias
A: 

I've always liked

Debug.WriteLine( ex.ToString() );
Paul Alexander
It's not that simple. I want to read the remote server error. Which in this case is "localhost" coincidentally.
Jader Dias
Ahh..missed the concept there. Still calling ToString will usually dump any diagnostic info for most exceptions. Even Web/Http exceptions.
Paul Alexander
+5  A: 

Web servers often return an error page with more details (either HTML or plain text depending on the server). You can grab this by catching WebException and reading the response stream from its Response property.

Christian Hayter
+1  A: 

You should use HttpWebRequest and HttpWebResponse. WebClient is the simplest thing to use to do basic web communication, but it does not provide the functionality you need. I think it's better to do this because it will not throw an exception.

Josh Stodola
A: 

I found useful information for debugging this way:

        catch (WebException ex)
        {
            HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response;
            String details = "NONE";
            String statusCode = "NONE";
            if (httpWebResponse != null)
            {
                details = httpWebResponse.StatusDescription;
                statusCode = httpWebResponse.StatusCode.ToString();
            }

            Response.Clear();
            Response.Write(ex.Message);
            Response.Write("<BR />");
            Response.Write(ex.Status);
            Response.Write("<BR />");
            Response.Write(statusCode);
            Response.Write("<BR />");
            Response.Write(details);
            Response.Write("<BR />");
            Response.Write(ex);
            Response.Write("<BR />");
        }
MrPhil