现记录用户登陆信息(记住登陆效果)cookie
本文讲述了使用cookies实现网站记住登陆效果,效果以下:网站
主要实现方法,当用户选择记住登陆时创建cookies保存用户名和用户密码,当用户登陆不选择记住登陆时,从新创建一个cookies,设置以过时,并将保存用户名、密码的子cookies赋null值,代码以下:spa
//记住登陆名密码blog
if (SAVAUSERID == "on")input
{it
HttpCookie cookie = new HttpCookie("COOKIE_NAME_FOR_USER");cookies
cookie.Expires = DateTime.Now.AddYears(1);class
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();