与同一服务器上的cookie容器的HttpWebRequest.GetResponse非常慢

时间:2012-05-25 22:24:12

标签: c# cookies httpwebrequest

在我的安全网站上,我通过HttpWebRequest.GetResponse()访问同一网站的页面(有一个原因)。如果我将超时设置为高可行,则运行大约需要两分钟。在浏览器中加载同一页面只需不到两秒钟。你会在下面的代码中看到我的一些实验:加载Google很快,加载一个没有内容的安全页面很慢,加载一个不安全的(http)页面很慢。但是,如果我注释掉我添加cookie的代码部分,则不安全页面会快速运行。请注意,Cookie不会影响对Google的通话。似乎服务器必须永远处理cookie。知道为什么,或者我能做些什么来解决它?

public static string GetPageHtmlSecure(string url, HttpContext inContext = null)
{
    string pageHtml;
    HttpContext context;


    if (inContext != null)
    {
        context = inContext;
    }
    else
    {
        context = HttpContext.Current;
    }

    // we've already validated the server's ID, don't need to do it again
    ServicePointManager.ServerCertificateValidationCallback += skipCertValidation;

    // create web request
    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");

    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://secure/page/no/content");
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://not/secure/page/");
    // attach the cookies the user has to this request
    request.CookieContainer = new CookieContainer();
    Cookie c = new Cookie();
    for (int i = 0; i < context.Request.Cookies.Count; i++)
    {
        c.Name = context.Request.Cookies[i].Name;
        c.Value = context.Request.Cookies[i].Value;
        c.Domain = request.RequestUri.Host;
        c.Expires = context.Request.Cookies[i].Expires;
        c.Path = context.Request.Cookies[i].Path;
        c.Secure = context.Request.Cookies[i].Secure;

        request.CookieContainer.Add(c);
    }

    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
    request.Method = "GET";
    request.ContentType = "text/xml";
    request.Timeout = 200000;
    request.ReadWriteTimeout = 200000;
    request.KeepAlive = false;
    request.Proxy = null;

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (System.IO.StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            pageHtml = sr.ReadToEnd();
        }
    }
    return pageHtml;
}

0 个答案:

没有答案