asp.net记住我功能

时间:2024-09-09 10:07:32
登录页面的记住我功能  
不能用session的原因:sessionID是以cookie的形式存在浏览器端的内存中  如果用户把浏览器关闭 则sessionID就消失    
但是服务器端的session在过期时间内还是存在的 等到浏览器在 默认的过期时间内(20分钟)不在向服务器发送请求 则过了20分钟 session销毁!
前端简单模拟:
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="RememberMe.Login" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
window.onload = function () {
document.getElementById('btnClose').onclick = function () {
window.close();
};
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center;">
<table>
<tr>
<td>用户名:
<input type="text" name="txtName" value="<%=uName %>" /></td>
</tr>
<tr>
<td>密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="txtPwd" value="<%=pwd %>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="checkbox" name="rememberMe" value="1" checked="checked" />记住我</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登录" />
<input type="button" value="关闭" id="btnClose" /></td>
</tr>
</table> </div>
</form>
</body>
</html>

Login.aspx

后台代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace RememberMe
{
public partial class Login : System.Web.UI.Page
{
protected string uName;
protected string pwd;
protected void Page_Load(object sender, EventArgs e)
{ if (Request.Cookies["user"] != null)
{
uName = Request.Cookies["user"].Values["n"];
pwd = Request.Cookies["user"].Values["p"];
}
if (IsPostBack)
{
string userName = Request.Form["txtName"];
string userPwd = Request.Form["txtPwd"];
if (!string.IsNullOrEmpty(Request.Form["rememberMe"]))
{
if (userName == "admin" && userPwd == "admin")
{
AlertAndRedirect("Index.aspx?n=" + userName, "登录成功");
HttpCookie cookie = new HttpCookie("user");
cookie["n"] = userName;
cookie["p"] = userPwd;
cookie.Expires = DateTime.Now.AddDays();
Response.Cookies.Add(cookie);
}
else
{
AlertAndRedirect("Login.aspx", "登录失败");
Response.Cookies["user"].Expires = DateTime.Now.AddDays(-);
}
}
else
{
Response.Cookies["user"].Expires = DateTime.Now.AddDays(-);
if (userName == "admin" && userPwd == "admin")
{
AlertAndRedirect("Index.aspx?n=" + userName, "登录成功");
}
else
{
AlertAndRedirect("Login.aspx", "登录失败");
}
}
} }
private void AlertAndRedirect(string redirectURL, string msg)
{
Response.Write("<script>alert('" + msg + "');window.location.href='" + redirectURL + "';</script>");
}
}
}

Login.aspx,cs

基本功能实现。下载:http://www.cnblogs.com/wolf-sun/admin/Files.aspx