我正在使用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。 救救我!
答案 0 :(得分:1)
可能的情况:
请使用Fiddler或其他HTTP观察工具查看从服务器到浏览器和您的应用程序的响应。服务器很可能只返回3个cookie。