net mvc中实现记录用户登录信息(记住登录效果)
现记录用户登录信息(记住登录效果)
本文讲述了使用cookies实现网站记住登录效果,效果如下:
主要实现方法,当用户选择记住登录时建立cookies保存用户名和用户密码,当用户登录不选择记住登录时,重新建立一个cookies,设置以过期,并将保存用户名、密码的子cookies赋null值,代码如下:
//记住登录名密码
if (SAVAUSERID == "on")
{
HttpCookie cookie = new HttpCookie("COOKIE_NAME_FOR_USER");
cookie.Expires = DateTime.Now.AddYears(1);
cookie["COOKIE_USER_NAME"] = LOGINNAME;
cookie["COOKIE_USER_PASS"] = LOGINPASSWORD;
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
else
{
HttpCookie cookie = new HttpCookie("COOKIE_NAME_FOR_USER");
cookie.Expires = DateTime.Now.AddYears(-1);
Request.Cookies.Add(cookie);
cookie["COOKIE_USER_NAME"] = null;
cookie["COOKIE_USER_PASS"] = null;
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
前台页面代码:
用户名称:<input class="input" id="LOGINNAME" name="LOGINNAME" style="width:150px" type="text" value="<%=ViewData["username"]%>" />
用户密码:<input class="input" id="LOGINPASSWORD" name="LOGINPASSWORD" style="width:150px" type="password" value="<%=ViewData["userpass"]%>"/>
<input type="submit" name="button" class="button" value="登录系统" />
<input type="checkbox" name="SAVAUSERID" id="SAVAUSERID" <%= ViewData["CHECKBOX"]%>/><span style="font-size: 12px;">记住登录</span>
其中ViewData在进入登陆页面时判断cookies的值是否为空,如果不为空就赋值,代码如下:
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("COOKIE_NAME_FOR_USER");
ViewData["username"] = (cookie == null ? "" : cookie["COOKIE_USER_NAME"].ToString().Trim());
ViewData["userpass"] = (cookie == null ? "" : cookie["COOKIE_USER_PASS"].ToString().Trim());
if (cookie != null)
ViewData["CHECKBOX"] = "checked=checked";
eturn View();