February 9, 2006
Sending persistent cookies in a WebRequest
As I wrote here, I use a WebRequest to post the initial image data to FogBugz rather than control IE using COM automation. The main advantage of using a WebRequest instead of automating IE is that I am not tied to IE. The main disadvantage is that a WebRequest will not naturally send any cookies. FogBugz uses a persistent cookie to automatically log you in.
There is a field in the WebRequest called CookieContainer. But it will not load your persistent cookies for you. You have to do this with your own code. Unfortunately there is no managed API for doing this. There is a Windows API in wininet.dll for doing this called InternetGetCookie. First I looked at pinvoke.net to see if there was a good example. I did not find one, but Google turned up this one on torsten’s blog.
I tried using the CookieContainer.SetCookies method just like torsten did, but it choked on one of the cookies (InternetGetCookie found 3 for my FogBugz url…some are probably for other apps on the same site). So I added code to parse the cookies my self and add them to CookieContainer as a collection.
private static System.Net.CookieCollection RetrieveIECookiesForUrl(Uri url)
{
System.Net.CookieCollection cookies = new System.Net.CookieCollection();
System.Text.StringBuilder cookieHeader = new System.Text.StringBuilder(new string(' ', 256), 256);
int datasize = cookieHeader.Length;
try
{
if (!(wininet.InternetGetCookie(url.ToString(), null, cookieHeader, ref datasize)))
{
if (0 >= datasize)
{
return cookies;
}
else
{
cookieHeader = new System.Text.StringBuilder(datasize);
wininet.InternetGetCookie(url.ToString(), null, cookieHeader, ref datasize);
}
}
foreach (string cookiestring in cookieHeader.ToString().Split(' '))
{
string cookieName = cookiestring.Split('=')[0];
string cookieValue = cookiestring.Split('=')[1];
if (cookieValue.EndsWith(";"))
{
cookieValue = cookieValue.Substring(0, cookieValue.Length - 1);
}
System.Net.Cookie cookie = new System.Net.Cookie(cookieName, cookieValue);
cookies.Add(cookie);
}
}
catch (Exception ex)
{
MessageBox.Show("RetrieveIECookiesForUrl failed: " + ex.ToString());
}
return cookies;
}
This site looks much better in a browser that supports current web standards, but it is accessible to any browser.
Download one now
Some parts of this site will not work effectively on this older browser.
Please consider
updating your browser