views:

491

answers:

3

Hi, How to let Httpwebresponse ignore the 404 error and continue with it? It's easier than looking for exceptions in input as it is very rare when this happens.

A: 

If you look at the properties of the WebException that gets thrown, you'll see the property Response. Is this what you are looking for?

spender
+3  A: 
    try
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mysite.com");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();          
    }
    catch(WebException ex)
    {
        HttpWebResponse webResponse = (HttpWebResponse)ex.Response;          
        if (webResponse.StatusCode == HttpStatusCode.NotFound)
        {
            //Handle 404 Error...
        }
    }
Phaedrus
I meant to read the 404 document as if it was a normal because I'm parsing it, it just won't go through regexes...
Skuta
+2  A: 

I'm assuming you have a line somewhere in your code like:

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Simply replace it with this:

HttpWebResponse response;

try
{
    response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    response = ex.Response as HttpWebResponse;
}
Adam Maras
I meant to read the 404 document as if it was a normal because I'm parsing it, it just won't go through regexes...
Skuta
Yes, this will do just that. After this block of code executes, `response` will be the response stream from *whatever* was returned, no matter what the HTTP status code is.
Adam Maras