C# - HttpWebResponse重定向检查器

Sha*_*neC 1 c# redirect httpwebrequest httpwebresponse

我正在尝试编写一个重定向检查程序,我今天早上刚刚将这个解决方案捆绑在一起,所以它不是最有效的,但除了一件事,它做了我需要做的一切:

它只会在停止之前检查两个站点,没有错误发生,它只是在"request.GetResponse()上停止为HttpWebResponse;" 第三页的行.

我尝试过使用不同的网站并更改页面组合以进行检查,但它只检查了两个.

有任何想法吗?

        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");
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

除了一个WebException被抛出它会破裂的事实,我相信它刚刚停止的原因是你永远不会处理你的回应.如果您有多个URL实际由同一站点提供服务,则它们将使用连接池 - 并且不会丢弃响应,您不会释放连接.你应该使用:

using (var response = request.GetResponse())
{
    var httpResponse = (HttpWebResponse) response;
    // Use httpResponse here
}
Run Code Online (Sandbox Code Playgroud)

请注意,我不是用铸造这里as-如果响应不是一个HttpWebResponse,一个InvalidCastException在该行比更翔实的NullReferenceException下一行...