为什么 Request.Cookies 在 foreach 循环中返回字符串而不是 HttpCookie 对象?
-
06-07-2019 - |
题
今天早上我无意中看到了下面的代码片段,我很惊讶,因为它运行得很好。
请不要看它的逻辑,我只是好奇为什么 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];
其他提示
您可能想按索引循环访问 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);
}
由于您也可以通过数字索引获取 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]));
不隶属于 StackOverflow