您的位置:首页 > 运维架构 > 网站架构

在网站中使用Cookie的简单例子

2010-06-23 17:30 323 查看
前台放一个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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: