一、页面布局
[code] <table cellpadding=\"1\" cellspacing=\"0\" style=\"border-collapse:collapse;\"><tr><td align=\"center\" colspan=\"2\">登录</td></tr><tr><td align=\"right\"><asp:Label ID=\"UserNameLabel\" runat=\"server\" AssociatedControlID=\"UserName\">用户名:</asp:Label></td><td><asp:TextBox ID=\"UserName\" runat=\"server\"></asp:TextBox><asp:RequiredFieldValidator ID=\"UserNameRequired\" runat=\"server\"ControlToValidate=\"UserName\" ErrorMessage=\"必须填写“用户名”。\" ToolTip=\"必须填写“用户名”。\"ValidationGroup=\"Login2\" Display=\"Dynamic\">账号不能为空</asp:RequiredFieldValidator></td></tr><tr><td align=\"right\"><asp:Label ID=\"PasswordLabel\" runat=\"server\" AssociatedControlID=\"Password\">密码:</asp:Label></td><td><asp:TextBox ID=\"Password\" runat=\"server\" TextMode=\"Password\"></asp:TextBox><asp:RequiredFieldValidator ID=\"PasswordRequired\" runat=\"server\"ControlToValidate=\"Password\" ErrorMessage=\"必须填写“密码”。\" ToolTip=\"必须填写“密码”。\"ValidationGroup=\"Login2\" Display=\"Dynamic\">密码不能为空</asp:RequiredFieldValidator></td></tr><tr><td align=\"right\" colspan=\"2\"><asp:Button ID=\"LoginButton\" runat=\"server\" CommandName=\"Login\" Text=\"登录\"ValidationGroup=\"Login2\" onclick=\"LoginButton_Click\" /></td></tr></table>
二、编辑配置文件
[code]<authentication mode=\"Forms\">//defaultUrl登录成功跳转的页面,loginUrl登录失败跳转的页面<forms defaultUrl=\"TaskList.aspx\" loginUrl=\"Login.aspx\"><credentials passwordFormat=\"Clear\">//设置用户名和密码<user name=\"admin\" password=\"admin\"/></credentials></forms></authentication>
[code]<location path=\"TaskList.aspx\"><system.web><authorization>//允许登录的用户<allow users=\"admin\"/>//阻止登录的用户,*表示所有匿名用户<deny users=\"*\"/></authorization></system.web></location>
三、后台代码
首先要引用:using System.Web.Security;
[code] protected void LoginButton_Click(object sender, EventArgs e){if (FormsAuthentication.Authenticate(UserName.Text,Password.Text)){FormsAuthentication.RedirectFromLoginPage(UserName.Text,true);}else{Response.Write(\"<script>alert(\'账号或密码不正确\');location.href=\'Login.aspx\'</script>\");}}