并非所有cookie都使用cookiecontainer保存

时间:2011-04-01 21:05:09

标签: c# cookies dns cookiecontainer

我正在使用Visual Studio 2010和.NET Framework 4.0。

代码:

public void LoginTo(string username, string password)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(this.Url + "login.php");
        string values =
            "username=" + username +
            "&password=" + password +
            "&redirect=" +
            "&autologin=on" +
            "&login=Log in";

        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = values.Length;
        req.KeepAlive = true;
        req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0";
        CookieContainer a = new CookieContainer();
        Uri uri = new Uri(this.Url);

        req.CookieContainer = a;

        ServicePointManager.Expect100Continue = false; // prevents 417 error

        using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.Default))
        {
            writer.Write(values);
        }

        HttpWebResponse response = (HttpWebResponse)req.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());

        formResponseWatcher formResponseWatcher = new formResponseWatcher();
        formResponseWatcher.SetResponseContent(reader.ReadToEnd());
        formResponseWatcher.Show();

        foreach (Cookie cookie in response.Cookies)
        {
            cookie.HttpOnly = true;
            Cookie = Cookie + cookie + ";";
        }
    }

问题是CookieContainer不包含所有cookie。 firefox中有5个cookie,但CookieContainer只检索3.我需要一直登录所有cookie。 我认为域名存在问题:.domain.com。 救救我!

1 个答案:

答案 0 :(得分:1)

可能的情况:

  • 服务器只返回3个cookie。其他Cookie可以在JavaScript代码中设置,也可以由其他请求设置
  • set-cookie标题格式错误,因为.Net无法解析,但对Firefox来说没问题(这是unlikley案例)。
  • 浏览器也可能会发送一些额外信息(即引荐标题),使服务器添加额外的cookie。

请使用Fiddler或其他HTTP观察工具查看从服务器到浏览器和您的应用程序的响应。服务器很可能只返回3个cookie。