Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Request.Cookies return string instead of HttpCookie object in foreach loop?

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);
    }
}
like image 732
Tien Do Avatar asked Jun 20 '09 07:06

Tien Do


3 Answers

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

like image 65
Charles Ma Avatar answered Nov 05 '22 01:11

Charles Ma


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);
}
like image 9
Chris Thompson Avatar answered Nov 05 '22 02:11

Chris Thompson


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]));
like image 5
aclemmensen Avatar answered Nov 05 '22 00:11

aclemmensen