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

使用COOKIE对像实现保存用户基本信息(结合Session),ASP.Net实现用户登录全过程

2012-04-13 08:50 1291 查看
1.创建一个WEB用户控件页面

。添加两个HTml 客户端DIV 并专为服务控件 前台代码如下

<div id="divLogin" runat="server"> ……</div>

<div id="divMain" runat="server" > ……</div>

。在div divLogin 中添加 Label(用户名) textBox(用户名) Label( 密码) textBOx(密码) Checkbox(记住我) button(登入)

。在div DivMain 中 添加 Label(HI,) Label(XXX)

2.WEB用户控件的后台代码实现

protected void Page_Load(object sender, EventArgs e)
{
//判断是否有Cookie信息可读
if (Request.Cookies.Get("loginUserName") != null)
{
//将Cookie中的登录信息读取出来保存到Session["loginUser"]中
Session["loginUser"] = Request.Cookies["loginUserName"].Value;
}

//通过判断Session["loginUser"]的值是否为空位判断是否登陆过,以及显示哪一个Div
if (Session["loginUser"] == null)
{
this.divLogin.Visible = true;
this.divMain.Visible = false;
}
else
{
this.divLogin.Visible = false;
this.divLoginMain.Visible = true;
this.lblUserMessage.Text = Session["loginUser"].ToString();
}
}
protected void btnLogin_Click(object sender, EventArgs e) //登录按钮Click事件
{
//保存登陆信息到Session["loginUser"]
if (ValidateUser(this.txtID.Text, this.txtPWD.Text))
{
Session["loginUser"] = this.txtID.Text;
//如果选择了保存Cookie
if (this.chkIsSaveCookie.Checked)
{
HttpCookie cookie = new HttpCookie("loginUserName",this.txtID.Text);
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
}
}
//刷新当前页面
Response.Redirect(Request.Url.ToString());
}

/// <summary>
/// 这里省略了访问数据库验证的过程
/// </summary>
/// <param name="id">登陆账号</param>
/// <param name="pwd">登陆密码</param>
/// <returns></returns>
public bool ValidateUser(string id, string pwd) //该方法用于数据验证,此处略
{
return true;
}

protected void btnSafeExit_Click(object sender, EventArgs e) //安全退出按钮Click事件
{
//清空Session中的用户信息
Session["loginUser"] = null;
//将本地Cookie中的信息移除----让Cookie过期
HttpCookie cookie = Request.Cookies["loginUserName"];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-10);
Response.Cookies.Add(cookie);
}

//刷新当前页面
Response.Redirect(Request.Url.ToString());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: