您的位置:首页 > 编程语言 > ASP

ASP.NET Cookies存值——登录次数、访问时间

2010-10-18 18:45 232 查看
ASP.NET Cookies存值,保存对应用户的登录次数和访问时间
我是刚开始用到Cookies存值,做这个期间,上次访问时间,还有就是登录次数,不管登录用户是谁,总是会递增,就这点小问题,让我闹心一天。现在终于出来了,记录下来,以后用到了,忘记了可以看看,或许也可以给其他人一点儿帮助。

新建实体类Users,下有属性 usename,封装

新建Web窗体Login

页面代码:

<body>
<form id="logForm" runat="server">
<div>

用户名:

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

  

<asp:Button ID="btnLogin" runat="server" Text=" 登 录 "
onclick="btnLogin_Click" />

</div>

</form>

</body>

后置代码:

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnLogin_Click(object sender, EventArgs e)
{
String loginName = getName();
if (Request.Cookies[loginName] == null)
{
HttpCookie hcookie = new HttpCookie(loginName);
hcookie.Values["username"] = this.txtName.Text; //登录用户名
hcookie.Values["lastVist"] = DateTime.Now.ToString(); //上次访问时间
hcookie.Values["nowVist"] = DateTime.Now.ToString(); //本次访问时间
hcookie.Values["count"] = "1"; //登录用户访问次数
hcookie.Expires = DateTime.Now.AddDays(30); //设置保存时间是30天
Response.Cookies.Add(hcookie);
}
else
{
HttpCookie hcookie = new HttpCookie(loginName);
hcookie.Values["username"] = this.txtName.Text;
String lastVist = Request.Cookies[loginName]["nowVist"];
hcookie.Values["lastVist"] = lastVist;
hcookie.Values["nowVist"] = DateTime.Now.ToString();
hcookie.Values["count"] = (Convert.ToInt32(Request.Cookies[loginName]["count"].ToString()) + 1).ToString();
hcookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(hcookie);
} Response.Redirect("Welcome.aspx");

}

private String getName()
{

String uname = this.txtName.Text;
Session["uname"] = uname;
return uname;
}

新建Web窗体Welcome

后置代码:

protected void Page_Load(object sender, EventArgs e)
{
if (Session["uname"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
String loginName = Session["uname"] as String;
Response.Write("登录用户是:" + Request.Cookies[loginName]["username"].ToString() + "<br/>");
Response.Write("本次登录时间是:" + Request.Cookies[loginName]["nowVist"].ToString() + "<br/>");
Response.Write("上次登录时间是:" + Request.Cookies[loginName]["lastVist"].ToString() + "<br/>");
Response.Write("当前用户登录次数是:" + Request.Cookies[loginName]["count"].ToString() + "<br/>");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: