1
votes

I am able to get numbers with enum as suggested by dtb in Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse. However, for moved permanently site also i am getting 200 (OK). What I want to see is 301 instead. Please help. My code is below. What could be wrong/needs to be corrected?

 public int GetHeaders(string url)
{
    //HttpStatusCode result = default(HttpStatusCode);
    int result = 0;
    var request = HttpWebRequest.Create(url);
    request.Method = "HEAD";
    try
    {
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            if (response != null)
            {
                result = (int)response.StatusCode; // response.StatusCode;
                response.Close();
            }
        }
    }
    catch (WebException we)
    {
        if (we.Response != null)
        {
            result = (int)((HttpWebResponse)we.Response).StatusCode;
        }

    }

    return result;
}

The tool where i am using this code is capable of showing 404, not existing domains but it is ignoring the redirects and shows the details about the redirected url. e.g if i put my older domain easytipsandtricks.com in the text field, it shows the results for tipscow.com (if you check easytipsandtricks.com in any checker tool online, you will notice that it is giving the correct redirect message - 301 Moved). Please help.

1

1 Answers

5
votes

You need to set HttpWebRequest.AllowAutoRedirect to false (default is true) for it to not automatically follow redirects (30x responses).

If AllowAutoRedirect is set to false, all responses with an HTTP status code from 300 to 399 is returned to the application.

Sample:

var request =  (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "HEAD";
request.AllowAutoRedirect = false;