将Cookie对象转换为字符串格式并返回

时间:2011-04-26 11:28:54

标签: c# asp.net serialization cookies

如何将cookie / cookie集合转换为其字符串表示形式? (在ASP.Net中)

我正在寻找的是

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

反之亦然。

1 个答案:

答案 0 :(得分:0)

你在找这样的东西吗?

   //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]));
   }