Share via


SqlMembershipProvider.ResetPassword(String, String) Metodo

Definizione

Reimposta la password di un utente su una nuova password generata automaticamente.

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

Parametri

username
String

Utente per il quale reimpostare la password.

passwordAnswer
String

Risposta per la password dell'utente specificato.

Restituisce

Nuova password per l'utente specificato.

Eccezioni

passwordAnswer non è valido.

-oppure-

L'account utente è attualmente bloccato.

username non è presente nel database di appartenenza.

-oppure-

L'operazione di modifica della password è stata annullata da un sottoscrittore all'evento ValidatingPassword e la proprietà FailureInformation era null.

-oppure-

Si è verificato un errore durante il recupero della password dal database.

username è una stringa vuota (""), contiene una virgola o è di lunghezza superiore a 256 caratteri.

-oppure-

passwordAnswer è una stringa vuota o ha una lunghezza superiore a 128 caratteri e RequiresQuestionAndAnswer è true.

-oppure-

passwordAnswer ha una lunghezza superiore a 128 caratteri dopo la codifica.

username è null.

-oppure-

passwordAnswer è null e RequiresQuestionAndAnswer è true.

Eccezione non gestita.

Esempio

Nell'esempio di codice seguente viene reimpostata la password di un utente e viene restituita la nuova password generata automaticamente.

Nota

In questo esempio viene usata la Membership classe per chiamare l'oggetto SqlMembershipProvider specificato come defaultProvider nel file di Web.config. Se è necessario accedere al provider predefinito come tipo SqlMembershipProvider, è possibile eseguire il cast della Provider proprietà della Membership classe. Per accedere ad altri provider configurati come tipo di provider specifico, è possibile accedervi tramite il nome configurato con la proprietà della Membership classe e eseguirne il Providers cast come tipo di provider specifico.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<!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.EnablePasswordReset)
  {
    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 reenter your user name.";

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

public void ResetPassword_OnClick(object sender, EventArgs args)
{
  string newPassword = "";

  try
  {
    newPassword = Membership.Provider.ResetPassword(UsernameTextBox.Text, AnswerTextBox.Text);
  }
  catch (NotSupportedException e)
  {
    Msg.Text = "An error has occurred resetting your password: " + e.Message + "." +
               "Please check your values and try again.";
  }
  catch (MembershipPasswordException e)
  {
    Msg.Text = "Invalid password answer. Please reenter the answer and try again.";
    return;
  }
  catch (System.Configuration.Provider.ProviderException e)
  {
    Msg.Text = "The specified user name does not exist. Please check your value and try again.";
  }

  if (newPassword != "")
  {
    Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword);
  }
  else
  {
    Msg.Text = "Password reset failed. Please reenter your values and try again.";
  }
}


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

<form id="form1" runat="server">
  <h3>Reset 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="ResetPasswordButton" Text="Reset Password" 
              OnClick="ResetPassword_OnClick" runat="server" Enabled="false" />

</form>

</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<!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(sender As Object, args As EventArgs)

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

  Msg.Text = ""

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

End Sub


Public 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 reenter your user name."

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

End Sub


Public Sub ResetPassword_OnClick(sender As Object, args As EventArgs)

  Dim newPassword As String = ""

  Try
    newPassword = Membership.Provider.ResetPassword(UsernameTextBox.Text, AnswerTextBox.Text)
  Catch e As NotSupportedException
    Msg.Text = "An error has occurred resetting your password: " & e.Message & "." & _
               "Please check your values and try again."
  Catch e As MembershipPasswordException
    Msg.Text = "Invalid password answer. Please reenter the answer and try again."
    Return
  Catch e As System.Configuration.Provider.ProviderException
    Msg.Text = "The specified user name does not exist. Please check your value and try again."
  End Try

  If newPassword <> "" Then
    Msg.Text = "Password reset. Your new password is: " & Server.HtmlEncode(newPassword)
  Else
    Msg.Text = "Password reset failed. Please reenter your values and try again."
  End If

End Sub


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

<form id="form1" runat="server">
  <h3>Reset 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="ResetPasswordButton" Text="Reset Password" 
              OnClick="ResetPassword_OnClick" runat="server" Enabled="False" />

</form>

</body>
</html>

Commenti

Questo metodo viene chiamato dalla Membership classe per reimpostare la password per un utente nel database SQL Server specificato nel file di configurazione dell'applicazione ASP.NET (Web.config) a un nuovo valore generato in modo casuale. Viene restituita la nuova password.

Nota

La password casuale creata dal ResetPassword metodo non è garantita per passare l'espressione regolare nella PasswordStrengthRegularExpression proprietà. Tuttavia, la password casuale soddisfa i criteri stabiliti dalle MinRequiredPasswordLength proprietà e MinRequiredNonAlphanumericCharacters .

Il ResetPassword metodo viene usato più comunemente quando la PasswordFormat proprietà è impostata su Hashed. Se un utente dimentica una password con hash, la password non può essere recuperata. Tuttavia, il provider può reimpostare la password in una nuova password generata automaticamente se l'utente fornisce la risposta password corretta.

Se viene fornita una risposta password errata al ResetPassword metodo, il contatore interno che tiene traccia dei tentativi di password non validi viene incrementato di uno. Ciò può comportare il blocco dell'utente e non è in grado di accedere fino a quando lo stato del UnlockUser blocco non viene cancellato da una chiamata al metodo. Se viene fornita la risposta password corretta e l'utente non è attualmente bloccato, il contatore interno che tiene traccia dei tentativi di risposta password non validi viene reimpostato su zero. Per altre informazioni, vedere le proprietà MaxInvalidPasswordAttempts e PasswordAttemptWindow.

È possibile chiamare il ResetPassword metodo direttamente ottenendo un riferimento all'istanza SqlMembershipProvider dalla Provider proprietà della Membership classe. La password generata sarà lunga almeno 14 caratteri o la lunghezza specificata nella MinRequiredPasswordLength proprietà e conterrà il numero di caratteri non alfanumerici specificati nella MinRequiredNonAlphanumericCharacters proprietà. La password non è garantita per passare l'espressione regolare contenuta nella PasswordStrengthRegularExpression proprietà, se specificata.

Gli spazi iniziali e finali vengono tagliati da tutti i valori dei parametri.

Si applica a

Vedi anche