1

I'm trying to code a redirect checker, the solution I have was just banged together this morning so it's not the most efficient but it does everything I need it to do apart from one thing:

It only ever checks two sites before stopping, no errors occur, it just stops on the "request.GetResponse() as HttpWebResponse;" line for the third page.

I've tried using different sites and changing the combination of pages to check but it only ever checks two.

Any ideas?

        string URLs = "/htmldom/default.asp/htmldom/dom_intro.asp/htmldom/dom_examples2.asp/xpath/default.asp";
        string sURL = "http://www.w3schools.com/";
        string[] u = Regex.Split(URLs, ".asp");

        foreach (String site in u)
        {
            String superURL = sURL + site + ".asp";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(superURL);

            request.Method = "HEAD";
            request.AllowAutoRedirect = false;

            var response = request.GetResponse() as HttpWebResponse;
            String a = response.GetResponseHeader("Location");

            Console.WriteLine("Site: " + site + "\nResponse Type: " + response.StatusCode + "\nRedirect page" + a + "\n\n");
        }

1 Answer 1

5

Aside from the fact that it will break if a WebException is ever thrown, I believe the reason it's just stopping is that you never dispose of your response. If you have multiple URLs served actually by the same site, they'll use a connection pool - and by not disposing of the response, you're not releasing the connection. You should use:

using (var response = request.GetResponse())
{
    var httpResponse = (HttpWebResponse) response;
    // Use httpResponse here
}

Note that I'm casting here instead of using as - if the response isn't an HttpWebResponse, an InvalidCastException on that line is more informative than a NullReferenceException on the next line...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jon, after putting in some error handling code, your solution worked perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.