Anyone know how I can convert Request.Cookies into a List<HttpCookie>? The following didn’t work as it throws an exception.
List<HttpCookie> lstCookies = new List<HttpCookie>(
Request.Cookies.Cast<HttpCookie>());
Exception: Unable to cast object of type ‘System.String’ to type ‘System.Web.HttpCookie’
The reason this happens is because the
NameObjectCollectionBasetype thatRequest.Cookiesderives from enumerates over the keys of the collection and not over the values. So when you enumerate over theRequest.Cookiescollection you are getting the keys:This means that the following will work:
I guess you could try the following which might be considered ugly but will work:
UPDATE:
As pointed out by @Jon Benedicto in the comments section and in his answer using the
AllKeysproperty is more optimal as it saves a cast: