views:

123

answers:

3

I'm trying to download a page using the WebRequest class in C#4.0. For some reason this page returns all the content correctly, but with a HTTP 500 internal error code.

Request.EndGetResponse(ar);

When the page returns HTTP 500 or 404, this method throws a WebException. How can I ignore this? I know it returns 500 but I still want to read the contents of the page / response.

A: 

Use a try / catch block to allow your program to keep running even if an exception is thrown:

try
{
    Request.EndGetResponse(ar);
}
catch (WebException wex)
{
    // Handle your exception here (or don't, to effectively "ignore" it)
}

// Program will continue to execute
Donut
A: 
try {
    resp = rs.Request.EndGetResponse(ar);
} 
catch (WebException ex) 
{ 
    resp = ex.Response as HttpWebResponse; 
}
peter
+2  A: 

You can a try / catch block to catch the exception and do additional processing in case of http 404 or 500 errors by looking at the response object exposed by the WebExeption class.

try
{
    response = (HttpWebResponse)Request.EndGetResponse(ar);
}
catch (System.Net.WebException ex)
{
    response = (HttpWebResponse)ex.Response;

    switch (response.StatusCode)
    {
        case HttpStatusCode.NotFound: // 404
            break;

        case HttpStatusCode.InternalServerError: // 500
            break;

        default:
            throw;
    }
}
Martin Hyldahl