views:

572

answers:

2

Hi,

This morning I accidentally saw the following snippet code, I was fairly surprised because it work very well.

Don't look at its logic please, I'm just curious why does the HttpCookieCollection (Request.Cookies in this case) return a string (cookie name) instead of a HttpCookie object in foreach loop. Is it a consistency issue because we normally get HttpCookie object in this collection by index/name?

Thanks,

foreach (string cookieKey in System.Web.HttpContext.Current.Request.Cookies)
{
    HttpCookie tmpCookie = System.Web.HttpContext.Current.Request.Cookies[cookieKey];
    if (tmpCookie != null && tmpCookie["RecentlyVisited"] != null)
    {
       cookie.Add(tmpCookie);
    }
}
+1  A: 

It makes more sense to iterate through a collection by the keys. That way you have access to both the keys and can easily access the value by calling System.Web.HttpContext.Current.Request.Cookies[cookieKey];

Charles Ma
A: 

You may want to loop through your cookies by index:

HttpCookieCollection MyCookieColl;
HttpCookie MyCookie;

MyCookieColl = Request.Cookies;

// Capture all cookie names into a string array.
String[] arr1 = MyCookieColl.AllKeys;

// Grab individual cookie objects by cookie name.
for (int i = 0; i < arr1.Length; i++) 
{
   MyCookie = MyCookieColl[arr1[i]];
   Debug.WriteLine("Cookie: " + MyCookie.Name);
   Debug.WriteLine("Expires: " + MyCookie.Expires);
   Debug.WriteLine("Secure:" + MyCookie.Secure);
}
Chris Thompson