让Cookies操作变得向Session一样简单

很多开发者都会觉得使用Session比使用Cookies简单,不需要实例化,直接可以使用索引器;那么接下来我们将让Cookies操作达到Session一样的操作简单

建立类:

C# 代码
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace testcookie
...{
public class CCookies
...{
static CCookies instance = null;
static readonly object padlock = new object();
private CCookies()
...{
}

public static CCookies Cookie ...{
get ...{
lock (padlock) ...{
if (instance == null)
instance
= new CCookies();
return instance;
}

}

}


public string this[string key]
...{
get
...{
return GetValue(key);
}

set
...{
Add(key, value);
}

}


/// <summary>
/// 添加Cookie 项
/// </summary>
/// <param name="key">键名</param>
/// <param name="value">键值</param>

public void Add(string key, string value)
...{
HttpCookie cookie
= HttpContext.Current.Request.Cookies["User"];
if (cookie == null)
...{
cookie
= new HttpCookie("User");
cookie.Expires
= DateTime.Now.AddDays(1);
}

cookie.Values[key]
= value;
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}


/// <summary>
/// 获取Cookie值
/// </summary>
/// <param name="key">键名</param>
/// <returns></returns>

public string GetValue(string key) ...{
HttpCookie cookie
= (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["User"];
if (cookie != null)
...{
return cookie.Values[key];
}

return string.Empty;
}


/// <summary>
/// 移除Cookie值
/// </summary>
/// <param name="key">键名</param>

public void Remove(string key)
...{
HttpCookie cookie
= HttpContext.Current.Request.Cookies["User"];
if (cookie != null)
...{
cookie.Values.Remove(key);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

}

/// <summary>
/// 清除 Cookie
/// </summary>

public void Clear() ...{
HttpCookie cookie
= (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["User"];
if (cookie != null)
...{
cookie.Expires
= System.DateTime.Now.AddDays(-2);
cookie.Values.Clear();
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

}

}

}

使用实例:

C# 代码
testcookie.CCookies.Cookie.Add("A", "a");
testcookie.CCookies.Cookie[
"B"] = "b";
testcookie.CCookies.Cookie[
"C"] = "c";

Response.Write(testcookie.CCookies.Cookie[
"A"]);
Response.Write(testcookie.CCookies.Cookie.GetValue(
"B"));
Response.Write(testcookie.CCookies.Cookie[
"C"] + "<br>");

testcookie.CCookies.Cookie.Clear();
Response.Write(testcookie.CCookies.Cookie[
"A"]);
Response.Write(testcookie.CCookies.Cookie.GetValue(
"B"));
Response.Write(testcookie.CCookies.Cookie[
"C"]);

现在是不是操作很简单了呢?

当然,上面的代码还只能完成初步的工作,向cookies的domain,以及有效期都不能灵活设置,我们可以根据自己的项目去修改。

posted @ 2009-02-03 14:19  leeolevis  阅读(191)  评论(0编辑  收藏  举报