当访问默认首页default.aspx时,会自动跳转到login.aspx页面上请求登录,随便输入用户名和密码,点击“登录”按钮,会回到首页,并显示当前登录的用户名。
Web.config
<configuration> <system.web> <compilationdebug="true"/> <authenticationmode="Forms"> <formsloginUrl="login.aspx"name=".ASPXFORMSAUTH"/> </authentication> <authorization> <denyusers="?"/> </authorization> </system.web> </configuration> |
default.aspx
<HTML> <HEAD> <TITLE>首页</TITLE> <scriptlanguage="VB"runat="server"> SubPage_Load(SenderAsObject,eAsEventArgs) Message.Text=String.Format("你好,{0}",Context.User.Identity.Name) EndSub subbtnSignout_Click(SenderasObject,EasEventArgs) FormsAuthentication.SignOut() Response.Redirect("login.aspx") endsub </script> </HEAD> <BODY> <asp:labelid="Message"runat="server"/> <br> <formmethod="post"runat="server"> <asp:buttonid="btnSignout"Text="退出登录"runat="server"OnClick="btnSignout_Click"/> </form> </BODY> </HTML> |
login.aspx
<HEAD> <TITLE>首页</TITLE> <scriptlanugage="c#"runat="server"> privatevoidPage_Load(objectsender,EventArgse) { if(Request.IsAuthenticated) Response.Redirect("default.aspx"); } voidbtnLogin_Click(Objectsender,EventArgse) { if(txtUsername.Text!=null&&txtUsername.Text!=String.Empty&&txtPassword.Text!=null&&txtPassword.Text!=String.Empty) FormsAuthentication.RedirectFromLoginPage(txtUsername.Text,true); else lblError.Text="错误的用户名/密码"; } </script> </HEAD> <BODY> <formmethod="post"runat="server"> <asp:Labelid="lblUsername"runat="server"Text="用户名:"/> <asp:Textboxid="txtUsername"runat="server"/> <br> <br> <asp:Labelid="lblPassword"runat="server"Text="密 码:"/> <asp:Textboxid="txtPassword"runat="server"TextMode="password"/> <br> <asp:buttonid="btnLogin"runat="server"Text="登录"OnClick="btnLogin_Click"/> </form> <hr> <br> <asp:Labelid="lblError"forecolor="red"runat="server"/> </BODY> </HTML> |