当访问默认首页default.aspx时,会自动跳转到login.aspx页面上请求登录,随便输入用户名和密码,点击“登录”按钮,会回到首页,并显示当前登录的用户名。
Web.config
1<configuration>
2<system.web>
3<compilation debug="true"></compilation>
4<authentication mode="Forms">
5<forms loginurl="login.aspx" name=".ASPXFORMSAUTH"></forms>
6</authentication>
7<authorization>
8<deny users="?"></deny>
9</authorization>
10</system.web>
11</configuration>
default.aspx
1<html>
2<head>
3<title>首页</title>
4<script language="VB" runat="server">
5Sub Page_Load(Sender As Object, e As EventArgs)
6Message.Text = String.Format("你好,{0}", Context.User.Identity.Name)
7End Sub
8sub btnSignout_Click(Sender as Object, E as EventArgs)
9FormsAuthentication.SignOut()
10Response.Redirect("login.aspx")
11end sub
12
13</script>
14</head>
15<body>
16<asp:label id="Message" runat="server"></asp:label>
17<br/>
18<form method="post" runat="server">
19<asp:button id="btnSignout" onclick="btnSignout_Click" runat="server" text="退出登录"></asp:button>
20</form>
21</body>
22</html>
login.aspx
1<head>
2<title>首页</title>
3<script lanugage="c#" runat="server">
4private void Page_Load(object sender, EventArgs e)
5{
6if (Request.IsAuthenticated)
7Response.Redirect("default.aspx");
8}
9void btnLogin_Click(Object sender, EventArgs e)
10{
11if (txtUsername.Text != null && txtUsername.Text != String.Empty && txtPassword.Text != null && txtPassword.Text != String.Empty)
12FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
13else
14lblError.Text = "错误的用户名/密码";
15}
16</script>
17</head>
1<body>
2<form method="post" runat="server">
3<asp:label id="lblUsername" runat="server" text="用户名:"></asp:label>
4
5<asp:textbox id="txtUsername" runat="server"></asp:textbox>
6<br/>
7<br/>
8<asp:label id="lblPassword" runat="server" text="密 码:"></asp:label>
9
10<asp:textbox id="txtPassword" runat="server" textmode="password"></asp:textbox>
11<br/>
12<asp:button id="btnLogin" onclick="btnLogin_Click" runat="server" text="登录"></asp:button>
13</form>
14<hr/>
15<br/>
16<asp:label forecolor="red" id="lblError" runat="server"></asp:label>
17</body>