SqlMembershipProvider.GetPassword(String, String) 方法

定义

从 SQL Server 成员资格数据库返回指定用户名的密码。

public:
 override System::String ^ GetPassword(System::String ^ username, System::String ^ passwordAnswer);
public override string GetPassword (string username, string passwordAnswer);
override this.GetPassword : string * string -> string
Public Overrides Function GetPassword (username As String, passwordAnswer As String) As String

参数

username
String

要为其检索密码的用户。

passwordAnswer
String

用户的密码提示问题答案。

返回

指定用户名所对应的密码。

例外

passwordAnswer 无效。

- 或 -

username 标识的成员资格用户已被锁定。

在成员资格数据库中找不到 username

- 或 -

从数据库中检索密码时出现错误。

某个参数值超过最大允许长度。

- 或 -

username 为空字符串 ("")、包含一个逗号或长度超过 256 个字符。

- 或 -

passwordAnswer 是空字符串且 RequiresQuestionAndAnswertrue

- 或 -

passwordAnswer 的长度超过 128 个字符。

- 或 -

编码版本的 passwordAnswer 的长度超过 128 个字符。

usernamenull

- 或 -

passwordAnswernull,而 RequiresQuestionAndAnswertrue

示例

下面的代码示例检索指定用户名的密码,并在电子邮件中将其发送给用户。

注意

对于需要高级别安全性的网站,不建议使用电子邮件以明文形式返回密码。 对于高安全性站点,建议使用加密(例如 SSL)返回密码。

注意

此示例使用 类调用 SqlMembershipProvider 指定为 defaultProvider Web.config 文件中的 Membership 。 如果需要以 类型 SqlMembershipProvider的形式访问默认提供程序,则可以强制转换 Provider 类的 Membership 属性。 若要以特定提供程序类型的形式访问其他配置的提供程序,可以使用 类的 Membership 属性按其配置的名称Providers对其进行访问,并将其强制转换为特定提供程序类型。

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Net.Mail" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Page_Load(object sender, EventArgs args)
{
  if (!Membership.EnablePasswordRetrieval)
  {
    FormsAuthentication.RedirectToLoginPage();
  }

  Msg.Text = "";

  if (!IsPostBack)
  {
    Msg.Text = "Please enter a user name.";
  }
  else
  {
    VerifyUsername();
  }
}


public void VerifyUsername()
{
    MembershipUser user = Membership.GetUser(UsernameTextBox.Text, false);

    if (user == null)
    {
      Msg.Text = "The user name " + Server.HtmlEncode(UsernameTextBox.Text) + " was not found. Please check the value and re-enter.";

      QuestionLabel.Text = "";
      QuestionLabel.Enabled = false;
      AnswerTextBox.Enabled = false;
      EmailPasswordButton.Enabled = false;
    }
    else
    {
      QuestionLabel.Text = user.PasswordQuestion;
      QuestionLabel.Enabled = true;
      AnswerTextBox.Enabled = true;
      EmailPasswordButton.Enabled = true;
    }
}


public void EmailPassword_OnClick(object sender, EventArgs args)
{
  // Note: Returning a password in clear text using email is not recommended for
  // sites that require a high level of security.

  try
  {
    string password = Membership.Provider.GetPassword(UsernameTextBox.Text, AnswerTextBox.Text);
    MembershipUser u = Membership.GetUser(UsernameTextBox.Text);
    EmailPassword(u.Email, password);
    Msg.Text = "Your password was sent via email.";
  }
  catch (MembershipPasswordException e)
  {
    Msg.Text = "The password answer is incorrect. Please check the value and try again.";
  }
  catch (System.Configuration.Provider.ProviderException e)
  {
    Msg.Text = "An error occurred retrieving your password. Please check your values " +
               "and try again.";
  }
}


private void EmailPassword(string email, string password)
{
  try
  {
    MailMessage Message = new MailMessage("administrator", email);
    Message.Subject = "Your Password";
    Message.Body = "Your password is: " + Server.HtmlEncode(password);

    SmtpClient SmtpMail = new SmtpClient("SMTPSERVER");
    SmtpMail.Send(Message);
  }
  catch 
  {
    Msg.Text = "An exception occurred while sending your password. Please try again.";
  }
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Retrieve Password</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Retrieve Password</h3>

  <asp:Label id="Msg" runat="server" ForeColor="maroon" /><br />

  Username: <asp:Textbox id="UsernameTextBox" Columns="30" runat="server" AutoPostBack="true" />
            <asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                        ControlToValidate="UsernameTextBox" ForeColor="red"
                                        Display="Static" ErrorMessage="Required" /><br />

  Password Question: <b><asp:Label id="QuestionLabel" runat="server" /></b><br />

  Answer: <asp:TextBox id="AnswerTextBox" Columns="60" runat="server" Enabled="false" />
          <asp:RequiredFieldValidator id="AnswerRequiredValidator" runat="server"
                                      ControlToValidate="AnswerTextBox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" Enabled="false" /><br />

  <asp:Button id="EmailPasswordButton" Text="Email My Password" 
              OnClick="EmailPassword_OnClick" runat="server" Enabled="false" />

</form>

</body>
</html>

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Net.Mail" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Public Sub Page_Load(ByVal sender As Object, ByVal args As EventArgs)

    If Not Membership.EnablePasswordRetrieval Then
      FormsAuthentication.RedirectToLoginPage()
    End If

    Msg.Text = ""

    If Not IsPostBack Then
      Msg.Text = "Please enter a user name."
    Else
      VerifyUsername()
    End If

  End Sub


  Private Sub VerifyUsername()

    Dim user As MembershipUser = Membership.GetUser(UsernameTextBox.Text, False)

    If user Is Nothing Then
      Msg.Text = "The user name " & Server.HtmlEncode(UsernameTextBox.Text) & " was not found. Please check the value and re-enter."

      QuestionLabel.Text = ""
      QuestionLabel.Enabled = False
      AnswerTextBox.Enabled = False
      EmailPasswordButton.Enabled = False
    Else
      QuestionLabel.Text = user.PasswordQuestion
      QuestionLabel.Enabled = True
      AnswerTextBox.Enabled = True
      EmailPasswordButton.Enabled = True
    End If

  End Sub


  Public Sub EmailPassword_OnClick(ByVal sender As Object, ByVal args As EventArgs)

    ' Note: Returning a password in clear text using email is not recommended for
    ' sites that require a high level of security.

    Try
      Dim password As String = Membership.Provider.GetPassword(UsernameTextBox.Text, AnswerTextBox.Text)
      Dim u As MembershipUser = Membership.GetUser(UsernameTextBox.Text)
      EmailPassword(u.Email, password)
      Msg.Text = "Your password was sent via email."
    Catch e As MembershipPasswordException
      Msg.Text = "The password answer is incorrect. Please check the value and try again."
    Catch e As System.Configuration.Provider.ProviderException
      Msg.Text = "An error occurred retrieving your password. Please check your values " & _
                 "and try again."
    End Try

  End Sub


  Private Sub EmailPassword(ByVal email As String, ByVal password As String)

    Try
      Dim Message As MailMessage = New MailMessage("administrator", email)
      Message.Subject = "Your Password"
      Message.Body = "Your password is: " & Server.HtmlEncode(password)
      
      Dim SmtpMail As SmtpClient = New SmtpClient("SMTPSERVER")
      SmtpMail.Send(Message)
    Catch
      Msg.Text = "An exception occurred while sending your password. Please try again."
    End Try

  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>Sample: Retrieve Password</title>
</head>
<body>
  <form id="form1" runat="server">
    <h3>
      Retrieve Password</h3>
    <asp:Label ID="Msg" runat="server" ForeColor="maroon" /><br />
    Username:
    <asp:TextBox ID="UsernameTextBox" Columns="30" runat="server" AutoPostBack="True" />
    <asp:RequiredFieldValidator ID="UsernameRequiredValidator" runat="server" ControlToValidate="UsernameTextBox"
      ForeColor="red" Display="Static" ErrorMessage="Required" /><br />
    Password Question: <b>
      <asp:Label ID="QuestionLabel" runat="server" /></b><br />
    Answer:
    <asp:TextBox ID="AnswerTextBox" Columns="60" runat="server" Enabled="False" />
    <asp:RequiredFieldValidator ID="AnswerRequiredValidator" runat="server" ControlToValidate="AnswerTextBox"
      ForeColor="red" Display="Static" ErrorMessage="Required" Enabled="False" /><br />
    <asp:Button ID="EmailPasswordButton" Text="Email My Password" OnClick="EmailPassword_OnClick"
      runat="server" Enabled="False" />
  </form>
</body>
</html>

注解

类调用 MembershipUser 此方法,以从 ASP.NET 应用程序的配置文件 (Web.config) 中指定的 SQL Server 数据库中检索用户的密码。

如果向 GetPassword 方法提供了错误的密码答案,则跟踪无效密码答案尝试的内部计数器将递增 1。 这可能会导致用户被锁定,并且无法登录,直到调用 UnlockUser 方法清除锁定状态。 如果提供了正确的密码答案,并且用户当前未锁定,则跟踪无效密码答案尝试的内部计数器将重置为零。 有关详细信息,请参阅 MaxInvalidPasswordAttemptsPasswordAttemptWindow 属性。

可以通过首先通过 Provider 类的 属性获取对 SqlMembershipProvider 实例的Membership引用来直接调用 GetPassword 方法。

如果 属性 PasswordFormat 设置为 Hashed,则 GetPassword 方法无法检索密码。 哈希密码是单向加密的,无法解密。 如果 属性 PasswordFormat 设置为 Hashed,并且 EnablePasswordRetrieval 设置为 trueProviderException 则在初始化提供程序时将引发 。

从所有参数值中剪裁前导空格和尾随空格。

适用于

另请参阅