James Jeffery
James Jeffery

Reputation: 12599

HttpClient - Ignoring 404

Quick question. HttpClient throws an exception on a 404 error, but the 404 page returned from the request is actually useful to my application in this instance. Is it possible to ignore a 404 response and processes the request as if it was a 200?

Upvotes: 2

Views: 3458

Answers (2)

Alex
Alex

Reputation: 23290

Hostname resolution failure is a different case than requesting a non-existing document to a known host, which must be handled separately. I suspect you're facing a resolution failure (since it would throw, whereas requesting a non-existing resource to a known host does not throw but gives you a nice "NotFound" response).

The following snippet handles both cases:

// urls[0] known host, unknown document
// urls[1] unknown host
var urls = new string[] { "http://www.example.com/abcdrandom.html", "http://www.abcdrandom.eu" };
using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = new HttpResponseMessage();
    foreach (var url in urls)
    {
        Console.WriteLine("Attempting to fetch " + url);
        try
        {
            response = await client.GetAsync(url);

            // If we get here, we have a response: we reached the host
            switch (response.StatusCode)
            {
                case System.Net.HttpStatusCode.OK:
                case System.Net.HttpStatusCode.NotFound: { /* handle 200 & 404 */ } break;
                default: { /* whatever */ } break;
            }
        }
        catch (HttpRequestException ex)
        {
            //kept to a bare minimum for shortness
            var inner = ex.InnerException as WebException;
            if (inner != null)
            {
                switch (inner.Status)
                {
                    case WebExceptionStatus.NameResolutionFailure: { /* host not found! */ } break;
                    default: { /* other */ } break;
                }
            }
        }
    }
}

The WebExceptionStatus enum contains many kinds of possible failures (including Unknown) for the code to handle.

Upvotes: 1

MichaelD
MichaelD

Reputation: 8787

You can read the content of the 404 using the stream from the exception

WebClient client = new WebClient();
try
{
    client.DownloadString(url);
}
catch (System.Net.WebException exception)
{
    string responseText;

    using (var reader = new System.IO.StreamReader(exception.Response.GetResponseStream()))
    {
        responseText = reader.ReadToEnd();
        throw new Exception(responseText);
    }
}

courtesy of someone else, but I cannot locate the source where i got this info

Upvotes: 2

Related Questions