5

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.

Skuta
  • 5,830
  • 27
  • 60
  • 68

3 Answers3

33

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
  • 26,269
  • 6
  • 65
  • 91
  • 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 Dec 07 '09 at 10:39
  • 1
    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 Dec 07 '09 at 11:15
  • 5
    Remeber that `HttpWebResponse` is `IDisposable` and needs to be wrapped in `using` block, otherwise you will hit concurrent http request limit. – skolima Jul 09 '13 at 21:40
  • Instead of the using calling response.Close() is enough? – mberacochea Oct 01 '14 at 20:22
  • Adam, this solved my issue, but why does it work? If it isn't found, how can it be in the exception details? Well known Microsoft secret? –  Nov 23 '15 at 17:15
  • @jp2code so just because a resource isn't found by the server doesn't mean it doesn't respond with *something*. Typically, when a response has a 404 Not Found status, the response body contains some information (maybe an error message or some other details). My answer also allows you to get the response body for other error status codes, so that you can get to whatever error information the server chooses to share with you. – Adam Maras Nov 23 '15 at 17:20
10
    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
  • 8,351
  • 26
  • 28
  • 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 Dec 07 '09 at 11:02
0

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
  • 117,338
  • 33
  • 229
  • 351