asp.net – 为什么Request.Cookies在foreach循环中返回字符串而不是HttpCookie对象?

今天早上我不小心看到以下代码段,我很惊讶,因为它工作得很好。

不要看它的逻辑,我只是​​好奇为什么HttpCookieCollection(在这种情况下是Request.Cookies)在foreach循环中返回一个字符串(cookie名称)而不是一个HttpCookie对象。这是一个一致性问题,因为我们通常通过索引/名称在此集合中获取HttpCookie对象?

谢谢,

foreach (string cookieKey in System.Web.HttpContext.Current.Request.Cookies)
{
    HttpCookie tmpCookie = System.Web.HttpContext.Current.Request.Cookies[cookieKey];
    if (tmpCookie != null && tmpCookie["RecentlyVisited"] != null)
    {
       cookie.Add(tmpCookie);
    }
}

解决方法

通过密钥迭代集合更有意义。这样你可以访问这两个密钥,并可以通过调用System.Web.HttpContext.Current.Request.Cookies [cookieKey]轻松访问该值。

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...