UserLogin 页面:
ButtonLogin_Click Event:
User user = new User(); if ( ValidateUser(user)) { if ( UserLogin(user)) { FormsAuthentication.SetAuthCookie(user.UserName, true); FormsAuthentication.RedirectFromLoginPage(user.UserName, true); } else lblMsg.Text = "Password is wrong"; } else lblMsg.Text = "User is not exist.";
Default 页面:
protected void Page_Load(object sender, EventArgs e) { HttpCookie myCount = new HttpCookie("Count"); DataSet objDataSet = new DataSet(); string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); if (!Page.IsPostBack) { if (Request.Cookies["Count"] == null) { myCount.Value = "true"; objDataSet.ReadXml(Server.MapPath("countdb/WebCount.xml")); objDataSet.Tables["MyCount"].Rows[0]["AllCount"] = Convert.ToInt64(objDataSet.Tables["MyCount"].Rows[0]["AllCount"]) + 1; objDataSet.WriteXml(Server.MapPath("countdb/WebCount.xml")); Response.Cookies.Add(myCount); lblAllCount.Text = objDataSet.Tables["MyCount"].Rows[0]["AllCount"].ToString(); } else { objDataSet.ReadXml(Server.MapPath("countdb/WebCount.xml")); lblAllCount.Text = objDataSet.Tables["MyCount"].Rows[0]["AllCount"].ToString(); } if (Application["user_sessions"] != null) { lblOnlineUserCount.Text = Application["user_sessions"].ToString(); } lblUserName.Text = ticket.Name; } }
用户注销:
protected void lbSignout_Click(object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); UserBLL.Logout(ticket.Name,ticket.IssueDate); FormsAuthentication.SignOut(); FormsAuthentication.RedirectToLoginPage(); }