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=" 登 录 "
οnclick="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/>");
}
}