在项目中,往往会有一些操作是限于登录后的用户,但怎么判断用户是否登录呢?
首先,写一个类:需要验证登录的页面继承这个类就可以了
View Code
public class CheckLogin:System.Web.UI.Page { protected override void OnInit(EventArgs e) { if (Session["user"]==null) { Common.WebCommon.GotoPage();//调用的方法是跳转页面的 } base.OnInit(e); } }
登录页代码:
View Code
public partial class Login : System.Web.UI.UserControl { BLL.Users userbll = new BLL.Users(); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { //校验登陆密码用户名 CheckLogin(); } else { //校验cookie CheckCookie(); } } /// <summary> /// 校验登陆 /// </summary> private void CheckLogin() { string txtName = Request.Form["txtName"]; string txtPass = Request["txtPass"]; if (userbll.CheckLoginId(txtName)) { Model.Users usermodel = userbll.CheckUserInfo(txtName, txtPass); Session["user"] = usermodel; if (usermodel != null) { //判断用户是否选择了复选框 if (!string.IsNullOrEmpty(Request.Form["CheckMe"])) { HttpCookie cookie1 = new HttpCookie("cp1", txtName); HttpCookie cookie2 = new HttpCookie("cp2", Entry(txtPass)); //cookie1.Expires.AddDays(3); cookie1.Expires = DateTime.Now.AddDays(3); cookie2.Expires = DateTime.Now.AddDays(3); Response.Cookies.Add(cookie1); Response.Cookies.Add(cookie2); } GotoPage("登陆成功!"); } else { Response.Redirect("/ShowMsg.aspx?msg=" + Server.UrlEncode("密码错误") + "&txt=" + Server.UrlEncode("登陆页面") + "&url=/regex/ULogin.aspx"); } } else { //用户名不存在 Response.Redirect("/ShowMsg.aspx?msg=" + Server.UrlEncode("用户名不存在") + "&txt=" + Server.UrlEncode("登陆页面") + "&url=/regex/ULogin.aspx"); } } /// <summary> /// 登陆后跳转 /// </summary> /// <param name="p"></param> private void GotoPage(string msg) { if (!string.IsNullOrEmpty(Request.QueryString["returnUrl"])) { Response.Redirect(Request.QueryString["returnUrl"]); } else { Response.Redirect("/ShowMsg.aspx?msg=" + Server.UrlEncode(msg) + "&txt=" + Server.UrlEncode("首页") + "&url=/ListBook/ListBook.aspx"); } } /// <summary> /// 校验cookie /// </summary> private void CheckCookie() { if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null) { string name = Request.Cookies["cp1"].Value.ToString(); string pwd = Request.Cookies["cp2"].Value.ToString(); Model.Users usermodel = userbll.CheckUserInfo(name); string EntypwdModel = Entry(usermodel.LoginPwd); //密码一致 if (EntypwdModel == pwd) { Session["user"] = usermodel; GotoPage("登陆成功"); } } else { Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1); } } public string Entry(string pwd) { return Web.HRMD5.GetMd5FromString(Web.HRMD5.GetMd5FromString(pwd)); } }