How do I convert the Cookies collection to a generic list? Easily

梦想的初衷 提交于 2020-01-02 01:43:05

问题


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'


回答1:


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



回答2:


If you really want a straight List<HttpCookie> with no key->value connection, then you can use Select in LINQ to do it:

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



回答3:


.Cookies.Cast<HttpCookie>(); tries to cast the collection of keys to a collection of cookies. So it's normal that you get an error :)

It's a name -> value collection, so casting to a list wouldn't be good.

I would try converting it to a dictionary.

For example:

Since Cookies inherits from NameObjectCollectionBase you can GetAllKeys(), and use that list to get all the values and put them in a Dictionary.

For example:

Dictionary cookieCollection = new Dictionary<string, object>();

foreach(var key in Request.Cookies.GetAllKeys())
{
    cookieCollection.Add(key, Request.Cookies.Item[key]);
}



回答4:


The question may be a bit old, but the answers here are not covering all cases, because as pointed out by @C.M. there can be multiple cookies with the same name.

So the easiest way is to loop the cookies 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]);
}


来源:https://stackoverflow.com/questions/2922762/how-do-i-convert-the-cookies-collection-to-a-generic-list-easily

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!