The reason this happens is because the NameObjectCollectionBase
type that Request.Cookies
derives from enumerates over the keys of the collection and not over the values. So when you enumerate over the Request.Cookies
collection you are getting the keys:
public virtual IEnumerator GetEnumerator()
{
return new NameObjectKeysEnumerator(this);
}
This means that the following will work:
string[] keys = Request.Cookies.Cast<string>().ToArray();
I guess you could try the following which might be considered ugly but will work:
List<HttpCookie> lstCookies = Request.Cookies.Keys.Cast<string>()
.Select(x => Request.Cookies[x]).ToList();
UPDATE:
As pointed out by @Jon Benedicto in the comments section and in his answer using the AllKeys
property is more optimal as it saves a cast:
List<HttpCookie> lstCookies = Request.Cookies.AllKeys
.Select(x => Request.Cookies[x]).ToList();