CookieContainer is driving me nuts, webResponse.Cookies always hascount of zero after first webReque

M

Mr Flibble

OK I logon to a web site and I manage to get an SMSESSION cookie that I
then store in a variable called _session (a class scoping variable). I
do this by calling a logon URL and setting a cookie to SMCHALLANGE=YES
to allow me to obtain a session. I then iterate the cookie collection
to extract the SMSESSION value. All is good (so far). This is when the
sky turns grey and the rain starts to fall. I then use this SMSESSION
in a web request and I get a response from the web server but I'm unable
to get any cookies. webResponse.Cookies collection from here on in
always has a count of zero. Whether I try using a new cookie container,
re-using the old one, no matter what I do I seem to be unable to
retrieve any subsequent cookies. I'm starting to think it may be better
to iterate the HTTP headers and get the values myself. The SMSESSION
value changes on each request and so not being able to get the updated
value is a major issue.


-- code snippet follows --

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";

webRequest.CookieContainer = new CookieContainer();
webRequest.CookieContainer.SetCookies(webRequest.RequestUri, _session);

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(payload);
webRequest.ContentLength = data.Length;
Stream newStream = webRequest.GetRequestStream();

newStream.Write(data, 0, data.Length);
newStream.Close();

HttpWebResponse webResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();

foreach (Cookie c in webResponse.Cookies)
{
if (c.Name == "SMSESSION")
{
_session = c.ToString();
break;
}
}

-- snip --
 
M

Mr Flibble

OK I cant work out why the cookie container is always empty but I wrote
my own cookie getter and it works ok now. Since the site was working I
knew it had to be returning the cookies in the headers even if the
WebRepsonse.Cookies had a count of 0. i.e. had to be that the
CookieContainer wasn't working correctly. Sure enough I was right :)

Thought I'd post this code here incase it helps anyone else in the same
boat.

foreach (string key in webResponse.Headers.Keys)
{
string[] values = webResponse.Headers.GetValues(key);
for (int i = 0; i < values.Length; i++)
{
if (key == "Set-Cookie")
{
if (values.Contains("SMSESSION"))
{
_session = values;
_log.Info("new session is:" + _session);
break;
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top