24

今天早上我无意中看到了下面的代码片段,我很惊讶,因为它运行得很好。

请不要看它的逻辑,我只是​​好奇为什么 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);
    }
}
4

3 回答 3

9

通过键遍历集合更有意义。这样您就可以访问这两个键,并且可以通过调用轻松访问该值System.Web.HttpContext.Current.Request.Cookies[cookieKey];

于 2009-06-20T07:57:13.037 回答
9

您可能希望按索引循环浏览您的 cookie:

HttpCookieCollection MyCookieColl;
HttpCookie MyCookie;

MyCookieColl = Request.Cookies;

// Capture all cookie names into a string array.
String[] arr1 = MyCookieColl.AllKeys;

// Grab individual cookie objects by cookie name.
for (int i = 0; i < arr1.Length; i++) 
{
   MyCookie = MyCookieColl[arr1[i]];
   Debug.WriteLine("Cookie: " + MyCookie.Name);
   Debug.WriteLine("Expires: " + MyCookie.Expires);
   Debug.WriteLine("Secure:" + MyCookie.Secure);
}
于 2009-06-20T08:07:59.067 回答
5

由于您也可以通过它们的数字索引获取 cookie,因此实际上可以扫描多个具有相同名称的 cookie,而无需复制到 CookieCollection 或类似的东西。

这应该可以解决问题:

var cookieName = "yourcookie";
var matches = cookies.AllKeys
    .Select((name, i) => new {name, i})
    .Where(x => x.name == cookieName)
    .Select(x => DoSomethingWithEachMatch(cookies[x.i]));
于 2013-11-13T08:42:21.857 回答