设置Cookies
<p>设置Cookies方法一:</p> <% if (Request.Cookies["myName"] == null) { Response.Cookies["myName"].Value = "linyongqin"; Response.Cookies["myName"].Expires = DateTime.Now.AddDays(30); } else { Response.Write("我的名字:" + Request.Cookies["myName"].Value); } %> <p>设置Cookies方法二:</p> <% if (Request.Cookies["myCookiesName"] == null) { HttpCookie myCookies = new HttpCookie("myCookiesName"); myCookies.Value = "yokin"; myCookies.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(myCookies); } else { HttpCookie myCookiesName = Request.Cookies["myCookiesName"]; Response.Write("我的Cookies名字:" + myCookiesName.Value); } %>
Asp.Net中Response.Cookies.Remove 无法删除COOKIE的问题解决方法
登陆功能经常需要使用Cookie来存储登陆信息,可是在开发过程中,经常发现cookie无法删除的问题。删除的代码无非就是找到Cookie并删除掉。
但是会发现
Response.Cookies.Remove 无法删除COOKIE
原因是,Cookies是继承集合对象,而微软似乎有没有去实现对应的Remove功能,所以无效。
我自己整了一个清楚所有cookie的简单方法。如下:
string[] cookieCollection = Request.Cookies.AllKeys; foreach (string cookieKey in cookieCollection) { HttpCookie cookie = Request.Cookies[cookieKey]; if (null != cookie) { cookie.Expires = DateTime.Now.AddDays(-1); //这个是重点,设置过期后要放进Response.Cookies中去 Response.Cookies.Add(cookie); } }