Jeroen Swart

.NET Architect

HttpWebRequest, HttpWebResponse and cookies

For one of my projects I'm working with HttpWebRequest and HttpWebResponse to retrieve data from a webserver. The code on the server is in PHP which uses cookies to keep track of sessions.

After some research I found the CookieContainer is to be created once and set on each request. My code initially looked something like this:

CookieContainer cookieContainer = new CookieContainer();

HttpWebRequest firstRequest = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

HttpWebResponse firstResponse = (HttpWebResponse)firstRequest.GetResponse();

HttpWebRequest secondRequest = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

HttpWebResponse secondResponse = (HttpWebResponse)secondRequest .GetResponse();

At first it appeared to work. After the first request, the cookies came back in both the response and the CookieContainer. But the second request didn't work, at least the server responded as if no cookies were sent.

With the aid of wireshark, I discovered that the cookies simply weren't sent. And after some debugging I found that the CookieContainer stores the cookies per domain in a domaintable. Although the domainname on each cookie is correct, the domainname in the table is prefixed with a dot ('.'). I'm assuming that the cookies aren't sent, because the prefixed domainname doesn't match the domain I'm sending the next request to.

If I add the cookies to the CookieContainer myself, after getting the response, the cookies are sent as they should and all he requests work fine. With some checks added, the code looks as follows:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.Cookies != null && response.Cookies.Count > 0)

I still feel I must have missed something because, according to each example I've found, just setting the CookieContainer should be enough for all to work. If anyone has a suggestion, please leave a comment. For now, I'm sticking with my workaround.

Pingbacks and trackbacks (1)+

Comments are closed