0

I apologise if this is an obvious, stupid or previously answered question... but I've been searching around for an answer for hours now and haven't found anything to help me.

I'm writing a simple application which generates a random string of characters, then appends the string to the URL of an image hosting site - the idea being it's a sort of image roulette. I'm using the following function to verify that the image exists:

private bool ImgVerifier(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Head;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            int statusCode = (int)response.StatusCode;

            if (statusCode == 302)
            {
                MessageBox.Show("Status: " + response.StatusCode.ToString() + " at URL: " + url);
                response.Close();
                return false;
            }
            else
            {
                MessageBox.Show("Status: " + response.StatusCode.ToString() + " at URL: " + url);
                response.Close();
                return true;
            }
        }

The issue I have is the function never seems to report anything other than an HTTP "OK" status. When checking the image URL on the SeoBook Server Header Checker site it reports the page as having a 302 error.

Whiskers
  • 1
  • 1

2 Answers2

0

302 is an HTTP redirect (not an error). The component you are using automatically follows redirects. HttpWebRequest.AllowAutoRedirect is true by default which is why you only see the end result of the OK when it successfully follows the redirect.

Avner
  • 4,286
  • 2
  • 35
  • 42
0

HttpWebRequest raises exceptions for many HTTP errors. For that reason, your code will never reach the int statusCode = (int)response.StatusCode;. To get those errors, wrap your code in a try...catch and inspect the WebException.Status property.

In the case of 302, HttpWebRequest redirects to the new page. If you set the AllowAutoRedirect property to false, all responses with an HTTP status codes from 300 to 399 are returned to the application.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55