net mvc中實現記錄用戶登陸信息(記住登陸效果)

現記錄用戶登陸信息(記住登陸效果)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="登陸系統" />&nbsp;&nbsp;

<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();

相關文章
相關標籤/搜索