在程序開發中,使用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)
{
//你沒有登錄
}
}
如果想在任何位置,想取出登錄ID:
復制代碼 代碼如下:
string memberId = InsusBiz.MemberId;
最後想說的,你想移除Cooke,就可以使用InsusBiz.RemoveInsusCookie就可以了,因為它會把Cookie的過期時間變更為過去。這個通常應用在用戶Sign out的事件上。