Previous     Next

Copying cookies across domains in ASP.Net

If you logging in to remote sites using HttpWebRequest then you are probably used to supplying a CookieContainer object to keep track of login sessions etc. However, sometimes a login will do a redirect, leaving your cookies referring to the login url and not usable on the next url.

Post login details to
Site redirects (302) to:

The login cookie is stuck on http://yourdomain/login and is not used at http://yourdomain/admin, so the login fails.

The key is to set:
WebRequestObject.AllowAutoRedirect = false
in the HttpWebRequest for http://yourdomain/login

Code to copy cookies:

Dim oOldCookies As New CookieContainer
Dim oNewCookies As New CookieContainer
Dim oOldCookiesCol As New CookieCollection

'Do HttpRequest on http://yourdomain/login, place cookies in oOldCookies
'Remember to set WebRequestObject.AllowAutoRedirect = false

oOldCookiesCollection = oOldCookies.GetCookies(New System.Uri(""))
For iC = 0 To oOldCookiesCol.Count - 1
     oNewCookies.Add(New Cookie(oOldCookiesCol(iC).Name, oOldCookiesCol(iC).Value, "", ""))

'Now do HttpRequest on http://yourdomain/admin, using oNewCookies

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. Easy Cross Domain Cookies (Sharing cookies between domains)
  2. How to set third-party cookies with iframe Facebook Applications
  3. Opening a new browser window with POST data
  4. SEOMoz Linkscape API wrapper in VB.Net

If you liked this, then subscribe to my RSS feed