下面的代码示例演示了一个 ASP.NET 应用程序的 Web.config 文件,该应用程序将 ASP.NET 成员资格提供程序用于 Forms 身份验证并要求对所有用户进行身份验证。
<configuration>
<connectionStrings>
<add name="SqlServices" connectionString="Data Source=MySqlServer;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />
</connectionStrings>
<system.web>
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration> 下面的代码示例演示使用 Forms 身份验证和 ASP.NET 成员资格的 ASP.NET 应用程序的登录页。
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<script runat="server">
Public Sub Login_OnClick(sender As Object, args As EventArgs)
If (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text)) Then
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked)
Else
Msg.Text = "Login failed. Please check your user name and password and try again."
End If
End Sub
</script>
<html>
<head>
<title>Login</title>
</head>
<body>
<form runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><P>
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><BR>
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><BR>
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" /> Check here if this is <u>not</u> a public computer.
</form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<script runat="server">
public void Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
else
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
</script>
<html>
<head>
<title>Login</title>
</head>
<body>
<form runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><P>
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><BR>
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><BR>
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" /> Check here if this is <u>not</u> a public computer.
</form>
</body>
</html>