疾风萧萧

See, this isn't the finish line.The future is the finish line......
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用户点击Log In按钮后发生了什么?

Posted on 2006-06-08 11:09  疾风  阅读(1229)  评论(0编辑  收藏  举报
    Asp.net2.0提供了一系列登录相关组件,其中的Login控件使用起来可谓是简单之至,只需要在Login控件的Authenticate事件处理方法中验证用户输入的帐号、密码的正确性,然后把其中AuthenticateEventArgs类型的参数的Authenticated属性改成true就算用户登录成功了:

1 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
2 {
3     if (UserIsValid(Login1.UserName, Login1.Password))
4     {
5         e.Authenticated = true;
6     }
7 }

    嗯,用户点击“Log In”按钮后发生了什么?凭什么Asp.net运行环境就相信用户已经登录成功,在以后的请求中不会中途调转到“登录”界面?我们就来看看吧。
    用Lutz Roeder's .NET Reflector打开System.Web.dll程序集,在System.Web.UI.WebControls名称空间里Login类的AttemptLogin方法中,你看到了什么?

 1 private void AttemptLogin()
 2 {
 3 
 4             LoginCancelEventArgs args1 = new LoginCancelEventArgs();
 5             this.OnLoggingIn(args1);
 6             if (!args1.Cancel)
 7             {
 8                   AuthenticateEventArgs args2 = new AuthenticateEventArgs();
 9                   this.OnAuthenticate(args2);//这里将执行我们的Login1_Authenticate方法
10                   if (args2.Authenticated)
11                   {
12                         //嘿,只是设置了一下AuthCookie而已
13                         FormsAuthentication.SetAuthCookie(this.UserNameInternal, this.RememberMeSet);
14                         this.OnLoggedIn(EventArgs.Empty);
15                         this.Page.Response.Redirect(this.GetRedirectUrl(), false);
16                   }
17 
18             }
19       }
20 }

    真的很简单。