在网站中使用Cookie的简单例子
前台放一个TextBox、一个Label、一个Button(value="注销")
后台:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string name = this.TextBox1.Text;
HttpCookie coolie = new HttpCookie("UserName");
coolie.Value = name;
coolie.Expires = DateTime.Now.AddDays(7);
this.Response.Cookies.Add(coolie);
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
//检查请求中的Cookie信息
HttpCookie cookie = this.Request.Cookies["UserName"];
if (cookie != null)
{
this.Label1.Text = string.Format("你的名字是:{0}", cookie.Value);
}
else
{
this.Label1.Text = "未知用户";
}
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
//通过创建Expires的过期时间来达到删除的目的
HttpCookie cookie = new HttpCookie("UserName");
cookie.Expires = new DateTime(1999, 1, 1);
this.Response.Cookies.Add(cookie);
}
}