在程序中使用Cookie集合(定义/新建/删除)及案例讲解
在程序开发中,使用Cookie时,很少使用如http://jb51.net/article/33590.htm的写法。习惯写成Cookie集合,什么叫做Cookie集合,即是说一个Cookie,它拥有多个值。下面一系列演示,是怎样创建Cookie集合与使用。
代码如下:
InsusBiz
using System;
using System.Web;
/// <summary>
/// Summary description for InsusBiz
/// </summary>
public class InsusBiz
{
private static HttpResponse Response
{
get
{
return HttpContext.Current.Response;
}
}
private static HttpRequest Request
{
get
{
return HttpContext.Current.Request;
}
}
//定义一个Cookie集合
private static HttpCookie InsusCookie
{
get
{
return Request.Cookies["InsusCookie"] as HttpCookie;
}
set
{
if (Request.Cookies["InsusCookie"] != null)
{
Request.Cookies.Remove("InsusCookie");
}
Response.Cookies.Add(value);
}
}
//New Cookie集合
private static HttpCookie NewInsusCookie
{
get
{
HttpCookie httpCookie = new HttpCookie("InsusCookie");
return httpCookie;
}
}
//Remove Cookie集合
public static void RemoveInsusCookie()
{
if (InsusCookie == null)
Response.Cookies.Remove("InsusCookie");
else
Response.Cookies["InsusCookie"].Expires = DateTime.Now.AddDays(-1);
}
//创建一个Cookie,判断用户登录状态
public static bool LoginOk
{
get
{
return InsusCookie == null ? false : bool.Parse(InsusCookie.Values["LoginOk"]);
}
set
{
HttpCookie httpCookie = InsusCookie == null ? NewInsusCookie : InsusCookie;
httpCookie.Values["LoginOk"] = value.ToString();
InsusCookie = httpCookie;
}
}
//创建登录用户的帐号,整站使用
public static string MemberId
{
get
{
return InsusCookie == null ? string.Empty : InsusCookie.Values["MemberId"];
}
set
{
HttpCookie httpCookie = InsusCookie == null ? NewInsusCookie : InsusCookie;
httpCookie.Values["MemberId"] = value;
InsusCookie = httpCookie;
}
}
//如果还有整站使用的Cookie可以写在此,可以参考LoginOK或MemberId的写法。
}
在应用时,你会看到InsusBiz类别下有LoginOk,MemberId和RemoveInsusCookie等属性:
在程序中怎样使用这些cookie呢?如在登录验证成功之后,你需要把登录状态与登录的ID写入Cookie中
InsusBiz.LoginOk = true;
InsusBiz.MemberId = xxx;
在判断用户是否登录时,可以这个去判断:
代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!InsusBiz.LoginOk)
{
//你没有登录
}
}
string memberId = InsusBiz.MemberId;
最后想说的,你想移除Cooke,就可以使用InsusBiz.RemoveInsusCookie就可以了,因为它会把Cookie的过期时间变更为过去。这个通常应用在用户Sign out的事件上。