ASP.NET 实现自动登录(自定义自动登录时间期限)

自动登录主要是实现了第一次登录后将用户账号和密码存放在Cookie中,在第二次登录时获取Cookie中的值实现自动登录

创建个登录页面:(添加一个CheckBox控件控制是否需要自动登录)

登录页面后台代码实现:

 1   protected void Page_Load(object sender, EventArgs e)
 2     {
 3         try
 4         {
 5             string testname = Request.Cookies["test"].Values["testname"];
 6             if (testname!="" && testname!=null) { 
 7             if(testname=="Test"){
 8                 string str = "index.aspx?testname=" + testname;
 9                 Response.Redirect(str);
10                 }
11             }
12         }
13         catch { }
14     }
15 
16 protected void submit_Click(object sender, EventArgs e)
17     {
18         string name = username.Text;
19         string passwords = password.Text;
20         if (name == "Test" && passwords == "Test")
21         {
22             if (logincheckbox.Checked == true)
23             {
24                 HttpCookie hc = new HttpCookie("test");
25                 hc.Values.Add("testname", "Test");
26                 hc.Expires = DateTime.Now.AddDays(7);
27                 Response.Cookies.Add(hc);
28             }
29             string str = "index.aspx?testname=" + name;
30             Response.Redirect(str);
31         }
32         else if (name != "Test" && passwords != "Test") {
33             namespan.InnerText = "用户错误❌";
34             passwordspan.InnerText = "密码错误❌";
35         }
36     }

每次需要登录时,代码先执行Page_Load方法,从而获取Cookie中的值,做出相应判断达到自动登录。

站在巨人的肩膀上真的会看的更远更清晰!

                           -----用志不分,乃凝于神

原文地址:https://www.cnblogs.com/xiong950413/p/9970490.html