If you are working with WebBrowser control and you want to make some WebRequest you need to synchronize the cookies.
And that would be the naive way to do it:
httpWebRequest.CookieContainer.SetCookies(
webBrowser.Document.Url,
webBrowser.Document.Cookie.Replace(';', ',')
); // THIS CODE IS WRONG!!
The problem is the HttpOnly cookies that are missing from Document.Cookie for security reasons.
The HttpOnly cookies are probably the most important ones that you need.
This article explains how to get them:
http://www.codeproject.com/KB/shell/RetrieveHttponlyCookies.aspx
Here is a more compact version of the function for C#:
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
const int INTERNET_COOKIE_HTTPONLY = 0x00002000;
public static string GetGlobalCookies(string uri)
{
uint datasize = 1024;
StringBuilder cookieData = new StringBuilder((int)datasize);
if (InternetGetCookieEx(uri, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)
&& cookieData.Length > 0)
{
return cookieData.ToString().Replace(';', ',');
}
else
{
return null;
}
}
And the usage would be:
httpWebRequest.CookieContainer.SetCookies(
webBrowser.Document.Url,
GetGlobalCookies(webBrowser.Document.Url.AbsoluteUri)
);