使用asp.net的cookie实现网站登录的验证。
将login页中的登录信息保存到login的Cookie中,转到Home页面时,利用得到的Cookie值实现自动登录。
文件:login.aspx:
代码:
<td>   <asp:DropDownList ID="time" runat="server"> <asp:ListItem Selected="True" Value="1">不保存</asp:ListItem> <asp:ListItem Value="14">两周</asp:ListItem> <asp:ListItem Value="30">一个月</asp:ListItem> <asp:ListItem Value="0">不创建</asp:ListItem> </asp:DropDownList> </td>
文件:login.aspx.cs
代码:
protected void Login_Click(object sender, EventArgs e) { //创建一个新的Cookie HttpCookie newCookie = new HttpCookie("User"); //往Cookie里面添加值,均为键/值对。Cookie可以根据关键字寻找到相应的值 newCookie.Values.Add("Name",nameID.Text.Trim()); newCookie.Values.Add("Pwd",pwdID.Text.Trim()); //设置Session的值
Session["Name"] = nameID.Text.Trim(); Session["Pwd"] = pwdID.Text.Trim(); if (time.SelectedValue == "14") { newCookie.Expires = DateTime.Now.AddDays(14); } else if (time.SelectedValue == "30") { newCookie.Expires = DateTime.Now.AddDays(30); } else if (time.SelectedValue == "0") { newCookie.Expires = DateTime.Now.AddDays(0); }
//Cookie的设置页面要用Response Response.AppendCookie(newCookie); Response.Redirect("Home.aspx"); }
//Home页面前台代码 home.aspx
<asp:Button ID="btnReset" runat="server" Text="注销" onclick="BTnReset_Click" Visible="False" />//Home页面后台代码 home.aspx.cs
protected void Page_Load(object sender, EventArgs e) { //获得login页面的Cookie值 要用Request HttpCookie newCookie = Request.Cookies["User"]; if (newCookie != null) { Response.Write("欢迎" + newCookie.Values["Name"] + "来到该网站," + "你的密码是:" + newCookie.Values["Pwd"]); BTnReset.Visible = true; } //获得login页面的session值 if (Session["Name"] != null) { Response.Write("欢迎" + Session["Name"] + "来到该网站," + "你的密码是:" + Session["Pwd"]); BTnReset.Visible = true; } else { Response.Write("您还没有登陆!<a href='Login.aspx'>返回登陆</a>"); } } protected void BTnReset_Click(object sender, EventArgs e) { HttpCookie newCookie = Request.Cookies["User"]; if (newCookie != null) { newCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(newCookie); Response.Redirect("Login.aspx"); } }