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

Nim*_*van 5 c# asp.net cookies serialization

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

我在寻找的是

cookie-collection  => "name1=value1 expires=date1; name2=value2 path=/test"
Run Code Online (Sandbox Code Playgroud)

反之亦然.

Ste*_*cya 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]));
   }
Run Code Online (Sandbox Code Playgroud)

  • 我现在有类似的东西。但它目前不处理诸如过期、路径、域等参数。我正在寻找一些我可以使用的库,而不是滚动我自己的代码(如果我可以避免它)。 (4认同)