直接看几段简单代码:
if (this.cbUserName.Checked == true) { SetMyCookie("UserName", txt_UserID.Text.Trim()); } else { HttpCookie aCookie; string cookieName; int limit = Request.Cookies.Count; for (int i = 0; i < limit; i++) { cookieName = Request.Cookies[i].Name; if (cookieName == "UserName") { aCookie = new HttpCookie(cookieName); aCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(aCookie); break; } } }
设置Cookie
public void SetMyCookie(string name, string vals) { HttpCookie cookie = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(vals, System.Text.Encoding.GetEncoding("utf-8"))); cookie.Expires = DateTime.Now.AddDays(30); HttpContext.Current.Response.Cookies.Add(cookie); }
获取Cookie
public string GetMyCookie(string name) { if (HttpContext.Current.Request.Cookies[name] != null) return System.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[name].Value, System.Text.Encoding.GetEncoding("utf-8")); return ""; }