Reputation: 123
After my question Can't login with HttpWebRequests, I successfully logged in. I get the page where it says "Thank you for logging in", but after that I don't seem to be logged in.
To me this looks like a cookie problem. In firebug the cookies appeared to be HttpOnly could that be a problem? How can I make the HttpWebRequest
use cookies?
Here's the code I use to login:
string url = "http://www.warriorforum.com/login.php?do=login";
var bytes = Encoding.Default.GetBytes(@"vb_login_username=USERNAME&cookieuser=1&vb_login_password=&s=&securitytoken=guest&do=login&vb_login_md5password=d9350bad28eee253951d7c5211e50179&vb_login_md5password_utf=d9350bad28eee253951d7c5211e50179");
var container = new CookieContainer();
var request = (HttpWebRequest)(WebRequest.Create(url));
request.CookieContainer = container;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.CookieContainer = container;
using (var requestStream = request.GetRequestStream())
requestStream.Write(bytes, 0, bytes.Length);
var requestResponse = request.GetResponse();
using (var responsStream = requestResponse.GetResponseStream())
if (responsStream != null)
{
using (var responseReader = new StreamReader(responsStream))
{
var responseStreamReader = responseReader.ReadToEnd();
richTextBox1.Text = responseStreamReader; //this is to read the page source after the request
}
}
}
Upvotes: 1
Views: 326
Reputation: 151588
The HttpWebRequest.CookieContainer
's manual page says:
The CookieContainer property provides an instance of the CookieContainer class that contains the cookies associated with this request.
You do:
var container = new CookieContainer();
So on every request, you begin with a new CookieContainer
without any cookies. Make container
a class member and only instantiate it once.
Upvotes: 2