Convert cookie to string format and vice versa

How can I convert a cookie / cookie collection to its string representation? (in ASP.Net)

What I'm looking for

cookie-collection  => "name1=value1 expires=date1; name2=value2 path=/test"

and vice versa.

+5
source share
1 answer

Are you looking for something like this?

   //Convert to string
   HttpCookieCollection source = new HttpCookieCollection();
   string result = source.Cast<HttpCookie>().
                   Aggregate(string.Empty, (current, cookie) => 
                   current + string.Format("{0}={1} ", cookie.Name, cookie.Value));


   //Convert back to collection
   HttpCookieCollection dest = new HttpCookieCollection();
   foreach (var pair in result.Split(' '))
   {
        string[] cookies = pair.Split('=');
        dest.Add(new HttpCookie(cookies[0],cookies[1]));
   }
0
source

All Articles