carck3r
carck3r

Reputation: 317

Not all cookies being saved using cookiecontainer

I'm using Visual studio 2010 and .NET Framework 4.0.

Code:

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 + ";";
        }
    }

The problem is that CookieContainer doesn't contain all cookies. There're 5 cookies in firefox, but CookieContainer retrieves only 3. I need all cookies to be logged in all the time. I think that there's a problem with domains like: .domain.com. Help me!

Upvotes: 0

Views: 1699

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

Possible cases:

  • there are just 3 cookies returned from the server. Other cookies are either set in JavaScript code or set by other requests
  • set-cookie header is malformed enough for .Net to fail parsing, but ok for Firefox (this is unlikley case).
  • It is also possible that browser sends some extra information (i.e. referrer header) that makes the server to add extra cookies.

Please use Fiddler or other HTTP watcher tool to see what response coming from the server to browser and to your application. It is likely server just returns 3 cookies.

Upvotes: 1

Related Questions