How to convert a collection of cookies to a general list? Easily

Does anyone know how I can convert Request.Cookies to List<HttpCookie> ? The following did not work as it throws an exception.

 List<HttpCookie> lstCookies = new List<HttpCookie>( Request.Cookies.Cast<HttpCookie>()); 

Exception: it is not possible to reset an object of type "System.String" to type "System.Web.HttpCookie"

+7
generics
source share
4 answers

The reason for this is because the type NameObjectCollectionBase , which Request.Cookies is derived from enumerations by collection keys, and not on top of the value. Therefore, when you list the Request.Cookies collection, you get 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 think 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 AllKeys more optimal since it saves the cast:

 List<HttpCookie> lstCookies = Request.Cookies.AllKeys .Select(x => Request.Cookies[x]).ToList(); 
+9
source share

If you really need a direct List<HttpCookie> without a key β†’ connection, you can use Select in LINQ to do this:

 var cookies = Request.Cookies.AllKeys.Select(x => Request.Cookies[x]).ToList(); 
+5
source share

.Cookies.Cast<HttpCookie>(); trying to pass a key collection to a cookie collection. So it's normal that you get an error message :)

This name is β†’ a collection of values, so listing is not good.

I would try to convert it to a dictionary.

For example:

Since Cookies inherits from NameObjectCollectionBase, you can GetAllKeys () and use this list to get all the values ​​and put them into the dictionary.

For example:

 Dictionary cookieCollection = new Dictionary<string, object>(); foreach(var key in Request.Cookies.GetAllKeys()) { cookieCollection.Add(key, Request.Cookies.Item[key]); } 
+2
source share

The question may be a little old, but the answers here do not cover all cases, because, as pointed out by @CM, there may be several cookies with the same name.

So the easiest way is to copy the cookie collection with a for loop:

 var existingCookies = new List<HttpCookie>(); for (var i = 0; i < _httpContext.Request.Cookies.Count; i++) { existingCookies.Add(_httpContext.Request.Cookies[i]); } 
0
source share

All Articles