服务器端操作Cookie,主要注意会使用以下三个类:
HttpCookie,HttpResponse,HttpRequest
关于HttpCookie:
属性 描述 例子 Domain 获取或设置与此Cookie关联的域 Expires 获取或设置域的过期时间 HasKeys 获取一个值,通过该值指示Cookie是否具有子键 HttpOnly 获取或设定一个值,该值指定Cookie是否可通过客户端脚本访问 Item HttpCookie.Values属性的快捷方式 Name 获取或设置Cookie的名称 Path 获取或设置要与当前Cookie一起传输的虚拟路径 Secure 获取或设定一个值,该值指示是否使用安全套接字段(SSL)传输Cookie Value 获取或设置Cookie的值 Values 获取单个Cookie对象所包含的键值对的集合 cookie.Values["username"]
-
添加Cookie
public partial class cookie_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//创建Cookie
HttpCookie cookie = new HttpCookie("User"); //对中文进行编码
cookie["username"] = HttpUtility.UrlEncode("张三");
cookie["password"] = "zhangsan";
//注意:此处不可缺少,此处缺少,则无法成功添加cookie
cookie.Expires = DateTime.Now.AddDays(2); //添加Cookie
Response.Cookies.Add(cookie);
}
} - 读取Cookie
public partial class cookie_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//获取Cookie
HttpCookie cookie = Request.Cookies["User"]; //对中文进行解码
//输出:
// 张三
// zhangsan
Response.Write(HttpUtility.UrlDecode(cookie["username"])+"<br/>"+cookie["password"]);
}
} - 修改Cookie
public partial class cookie_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Cookies["User"]["username"] = HttpUtility.UrlEncode("李四"); //对中文进行解码
//输出:
// 李四
Response.Write(HttpUtility.UrlDecode(Request.Cookies["User"]["username"]));
}
} - 删除Cookie
public partial class cookie_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//设置Cookie过期,客户端即可自动删除该Cookie
Response.Cookies["User"].Expires = DateTime.Now.AddDays(-1);
}
}