您的位置:首页 > 编程语言 > ASP

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

2011-03-22 14:22 931 查看
页面代码:

<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#代码:

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");
}
}

代码已经通过测试,需注意一点。由于不同的浏览器保存的Cookie不同(在IE上点击记住登陆名,在谷歌浏览器就需重新登陆)。

学习过程的点滴记录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐