Question

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);
    }
}
Was it helpful?

Solution

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];

OTHER TIPS

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);
}

Since you can get cookies by their numerical index as well it's actually possible to scan multiple cookies with the same name without having to copy to a CookieCollection or something like that.

This should do the trick:

var cookieName = "yourcookie";
var matches = cookies.AllKeys
    .Select((name, i) => new {name, i})
    .Where(x => x.name == cookieName)
    .Select(x => DoSomethingWithEachMatch(cookies[x.i]));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top