Tie*_* Do 21 asp.net 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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能希望通过索引遍历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);
}
Run Code Online (Sandbox Code Playgroud)
通过键迭代集合更有意义.这样您就可以访问这两个键,并可以通过调用轻松访问该值System.Web.HttpContext.Current.Request.Cookies[cookieKey];
小智 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]));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12296 次 |
| 最近记录: |