ASP.NET使用Cookie简单实现记住登陆状态功能

页面代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< html  xmlns="http://www.w3.org/1999/xhtml">
< head  runat="server">
     < title > title >
head >
< body >
     < form  id="form1" runat="server">
     < div >
         < ul  style="list-style-type: none">
             < li >用户名:< asp:TextBox  ID="TextBox1" runat="server"> asp:TextBox > li >
             < li >密 码: < asp:TextBox  ID="TextBox2" runat="server"> asp:TextBox > li >
         ul >
         < div  style="margin-left:50px">
             < asp:CheckBox  ID="ckbRemenber" runat="server" Text="记住登陆状态" Font-Size="10px" />
             < asp:Button  ID="btLogin" runat="server" Text="登陆" onclick="btLogin_Click" /> div >
     div >
     form >
body >
html >

后台C#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public  partial  class  Default3 : System.Web.UI.Page
{
     protected  void  Page_Load( object  sender, EventArgs e)
     {
         if  (!IsPostBack)
         {
             if  (Request.Cookies[ "UserName" ]!=  null // 从客户端读取cookie值
             {
                 Response.Redirect( "Default2.aspx" );
             }
         }
     }
     protected  void  btLogin_Click( object  sender, EventArgs e)
     {
         string  name = TextBox1.Text;
         string  pwd = TextBox2.Text;
         if  (ckbRemenber.Checked ==  true )
         {
             Response.Cookies[ "UserName" ].Value = name;   //将值写入到客户端硬盘Cookie
             Response.Cookies[ "UserName" ].Expires = DateTime.Now.AddMinutes(10); //设置Cookie过期时间
         }
         Response.Redirect( "Default2.aspx" );
     }
}
1
代码已经通过测试,需注意一点。由于不同的浏览器保存的Cookie不同(在IE上点击记住登陆名,在谷歌浏览器就需重新登陆)。

你可能感兴趣的:(c#)