Sometimes when you build a website, you need to remember the user login information. When you log in to the website next time, you don’t need to repeatedly enter your username and password. The principle is that the browser’s cookies remember the status!
So how did it be implemented specifically? Below, the blogger will post some of the code. If you want the full version of the demo, you can download it from Baidu Cloud and Mai Cloud.
Baidu Cloud Download Link: https://pan.baidu.com/s/19pL-koHI9UnVd4bK3Fpuyg Password: nud3
Jack Ma download link: https://gitee.com/WuFengZui/RememberLoginDemo [Those who do not have download links are all hooligans haha! ! 】
Let's take a look at the renderings first:
The following is the code to add cookies, but this method is encapsulated by me. For specific operations in the method, you can view the second code.
//Create cookies [prevent login information leakage, here Encode() is used to encrypt the information] SqlHelper.SetCookie("NameCookie", SqlHelper.Encode(UserName), DateTime.Now.AddDays(7)); SqlHelper.SetCookie("PwdCookie", SqlHelper.Encode(Pwd), DateTime.Now.AddDays(7)); //Getcookie string name = SqlHelper.GetCookieValue("NameCookie"); string pwd = SqlHelper.GetCookieValue("PwdCookie"); //Delete Cookie SqlHelper.RemoveCookie("NameCookie"); SqlHelper.RemoveCookie("PwdCookie");Encapsulation method to add cookies
/// <summary> /// Set the Cookie value and expiration time/// </summary> /// <param name="cookieName">Cookie name</param> /// <param name="value">Value</param> /// <param name="expires">Expiration time</param> public static void SetCookie(string cookieName, string value, DateTime expires) { HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName]; if (cookie != null) { cookie.Value = value; cookie.Expires = expires; HttpContext.Current.Response.Cookies.Add(cookie); } else { cookie = new HttpCookie(cookieName); cookie.Value = value; cookie.Expires = expires; HttpContext.Current.Response.Cookies.Add(cookie); } }Encapsulate method to obtain cookies
/// <summary> /// Get the value of the cookie/// </summary> /// <param name="cookieName">Cookie name</param> /// <returns></returns> public static string GetCookieValue(string cookieName) { HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName]; if (cookie == null) return ""; else return cookie.Value; }