在程式中使用Cookie集合(定義/建立/刪除)及案例講解

來源:互聯網
上載者:User

在程式開發中,使用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的事件上。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.