MembershipUser.ResetPassword MembershipUser.ResetPassword MembershipUser.ResetPassword MembershipUser.ResetPassword Method

Definición

Restablece la contraseña de un usuario a una nueva generada automáticamente.Resets a user's password to a new, automatically generated password.

Sobrecargas

ResetPassword() ResetPassword() ResetPassword() ResetPassword()

Restablece la contraseña de un usuario a una nueva generada automáticamente.Resets a user's password to a new, automatically generated password.

ResetPassword(String) ResetPassword(String) ResetPassword(String) ResetPassword(String)

Restablece la contraseña de un usuario a una nueva generada automáticamente.Resets a user's password to a new, automatically generated password.

ResetPassword() ResetPassword() ResetPassword() ResetPassword()

Restablece la contraseña de un usuario a una nueva generada automáticamente.Resets a user's password to a new, automatically generated password.

public:
 virtual System::String ^ ResetPassword();
public virtual string ResetPassword ();
abstract member ResetPassword : unit -> string
override this.ResetPassword : unit -> string
Public Overridable Function ResetPassword () As String

Devoluciones

Nueva contraseña del usuario de pertenencia.The new password for the membership user.

Excepciones

Este método no está disponible.This method is not available. Esto se puede producir si la aplicación está destinada a .NET Framework 4 Client Profile.NET Framework 4 Client Profile.This can occur if the application targets the .NET Framework 4 Client Profile.NET Framework 4 Client Profile. Para evitar esta excepción, reemplace el método o cambie la aplicación para que el destino sea la versión completa de .NET Framework.To prevent this exception, override the method, or change the application to target the full version of the .NET Framework.

Ejemplos

En el ejemplo de código siguiente se restablece la contraseña de un usuario y se devuelve la nueva contraseña generada automáticamente.The following code example resets a user's password and returns the new, automatically generated password. RequiresQuestionAndAnswer Tengafalseen cuenta que se supone que es.Note that RequiresQuestionAndAnswer is assumed to be false.

Importante

Este ejemplo contiene un cuadro de texto que acepta datos proporcionados por el usuario, que es una posible amenaza de seguridad.This example contains a text box that accepts user input, which is a potential security threat. De forma predeterminada, ASP.NET Web Pages valida que los datos proporcionados por el usuario no incluyen elementos HTML ni de script.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Para más información, consulte Información general sobre los ataques mediante scripts.For more information, see Script Exploits Overview.

<%@ 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">

MembershipUser u;

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

  Msg.Text = "";

  if (!IsPostBack)
  {
    Msg.Text = "Please supply a username.";
  }
  else
  {
    VerifyUsername();
  }
}


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

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

      ResetPasswordButton.Enabled = false;
    }
    else
    {
      ResetPasswordButton.Enabled = true;
    }
}

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

  u = Membership.GetUser(UsernameTextBox.Text, false);

  if (u == null)
  { 
    Msg.Text = "Username " + Server.HtmlEncode(UsernameTextBox.Text) + " not found. Please check the value and re-enter.";
    return;
  }

  try
  {
    newPassword = u.ResetPassword();
  }
  catch (MembershipPasswordException e)
  {
    Msg.Text = "Invalid password answer. Please re-enter and try again.";
    return;
  }
  catch (Exception e)
  {
    Msg.Text = e.Message;
    return;
  }

  if (newPassword != null)
  {
    Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword);
  }
  else
  {
    Msg.Text = "Password reset failed. Please re-enter 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>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 />

  <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">

Dim u As MembershipUser

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 supply a username."
  Else
    VerifyUsername()
  End If
End Sub

Public Sub VerifyUsername()
    u = Membership.GetUser(UsernameTextBox.Text, False)

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

      ResetPasswordButton.Enabled = False
    Else
      ResetPasswordButton.Enabled = True
    End If
End Sub

Public Sub ResetPassword_OnClick(sender As Object, args As EventArgs)
  Dim newPassword As String
  u = Membership.GetUser(UsernameTextBox.Text, False)

  If u Is Nothing Then
    Msg.Text = "Username " & Server.HtmlEncode(UsernameTextBox.Text) & " not found. Please check the value and re-enter."
    Return
  End If

  Try
    newPassword = u.ResetPassword()
  Catch e As MembershipPasswordException
    Msg.Text = "Invalid password answer. Please re-enter and try again."
    Return
  Catch e As Exception
    Msg.Text = e.Message
    Return
  End Try

  If Not newPassword Is Nothing Then
    Msg.Text = "Password reset. Your new password is: " & Server.HtmlEncode(newPassword)
  Else
    Msg.Text = "Password reset failed. Please re-enter 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>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 />

  <asp:Button id="ResetPasswordButton" Text="Reset Password" 
              OnClick="ResetPassword_OnClick" runat="server" Enabled="False" />

</form>

</body>
</html>

Comentarios

ResetPasswordllama al MembershipProvider.ResetPassword método del proveedor de pertenencia al que hace ProviderName referencia la propiedad para restablecer la contraseña del usuario de pertenencia a una nueva contraseña generada automáticamente.ResetPassword calls the MembershipProvider.ResetPassword method of the membership provider referenced by the ProviderName property to reset the password for the membership user to a new, automatically generated password. La nueva contraseña se devuelve al autor de la llamada.The new password is then returned to the caller.

Si EnablePasswordReset esfalse, el proveedor de pertenencia devolverá una excepción.If EnablePasswordReset is false, the membership provider will return an exception.

Si RequiresQuestionAndAnswer ResetPassword es true, debe usar la sobrecarga que toma una respuesta de contraseña como parámetro y proporciona la respuesta de la contraseña para el usuario de pertenencia.If RequiresQuestionAndAnswer is true, you must use the ResetPassword overload that takes a password answer as a parameter and supply the password answer for the membership user. Si se requiere una respuesta de contraseña y se proporciona una respuesta de contraseña incorrecta MembershipPasswordException , el proveedor de pertenencia produce una.If a password answer is required and an incorrect password answer is supplied, a MembershipPasswordException is thrown by the membership provider.

Consulte también:

ResetPassword(String) ResetPassword(String) ResetPassword(String) ResetPassword(String)

Restablece la contraseña de un usuario a una nueva generada automáticamente.Resets a user's password to a new, automatically generated password.

public:
 virtual System::String ^ ResetPassword(System::String ^ passwordAnswer);
public virtual string ResetPassword (string passwordAnswer);
abstract member ResetPassword : string -> string
override this.ResetPassword : string -> string
Public Overridable Function ResetPassword (passwordAnswer As String) As String

Parámetros

passwordAnswer
String String String String

Respuesta de contraseña correspondiente al usuario de pertenencia.The password answer for the membership user.

Devoluciones

Nueva contraseña del usuario de pertenencia.The new password for the membership user.

Excepciones

Este método no está disponible.This method is not available. Esto se puede producir si la aplicación está destinada a .NET Framework 4 Client Profile.NET Framework 4 Client Profile.This can occur if the application targets the .NET Framework 4 Client Profile.NET Framework 4 Client Profile. Para evitar esta excepción, reemplace el método o cambie la aplicación para que el destino sea la versión completa de .NET Framework.To prevent this exception, override the method, or change the application to target the full version of the .NET Framework.

Ejemplos

En el ejemplo de código siguiente se restablece la contraseña de un usuario y se devuelve la nueva contraseña generada automáticamente.The following code example resets a user's password and returns the new, automatically generated password.

Importante

Este ejemplo contiene un cuadro de texto que acepta datos proporcionados por el usuario, que es una posible amenaza de seguridad.This example contains a text box that accepts user input, which is a potential security threat. De forma predeterminada, ASP.NET Web Pages valida que los datos proporcionados por el usuario no incluyen elementos HTML ni de script.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Para más información, consulte Información general sobre los ataques mediante scripts.For more information, see Script Exploits Overview.

<%@ 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">

MembershipUser u;

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

  Msg.Text = "";

  if (!IsPostBack)
  {
    Msg.Text = "Please supply a username.";
  }
  else
  {
    VerifyUsername();
  }
}


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

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

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

public void ResetPassword_OnClick(object sender, EventArgs args)
{
  string newPassword;
  u = Membership.GetUser(UsernameTextBox.Text, false);

  if (u == null)
  { 
    Msg.Text = "Username " + Server.HtmlEncode(UsernameTextBox.Text) + " not found. Please check the value and re-enter.";
    return;
  }

  try
  {
    newPassword = u.ResetPassword(AnswerTextBox.Text);
  }
  catch (MembershipPasswordException e)
  {
    Msg.Text = "Invalid password answer. Please re-enter and try again.";
    return;
  }
  catch (Exception e)
  {
    Msg.Text = e.Message;
    return;
  }

  if (newPassword != null)
  {
    Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword);
  }
  else
  {
    Msg.Text = "Password reset failed. Please re-enter 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>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="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">

Dim u As MembershipUser

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 supply a username."
  Else
    VerifyUsername()
  End If
End Sub

Public Sub VerifyUsername()
    u = Membership.GetUser(UsernameTextBox.Text, False)

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

      QuestionLabel.Text = ""
      QuestionLabel.Enabled = False
      AnswerTextBox.Enabled = False
      ResetPasswordButton.Enabled = False
    Else
      QuestionLabel.Text = u.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
  u = Membership.GetUser(UsernameTextBox.Text, False)

  If u Is Nothing Then
    Msg.Text = "Username " & Server.HtmlEncode(UsernameTextBox.Text) & " not found. Please check the value and re-enter."
    Return
  End If

  Try
    newPassword = u.ResetPassword(AnswerTextBox.Text)
  Catch e As MembershipPasswordException
    Msg.Text = "Invalid password answer. Please re-enter and try again."
    Return
  Catch e As Exception
    Msg.Text = e.Message
    Return
  End Try

  If Not newPassword Is Nothing Then
    Msg.Text = "Password reset. Your new password is: " & Server.HtmlEncode(newPassword)
  Else
    Msg.Text = "Password reset failed. Please re-enter 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>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="ResetPasswordButton" Text="Reset Password" 
              OnClick="ResetPassword_OnClick" runat="server" Enabled="False" />

</form>

</body>
</html>

Comentarios

ResetPasswordllama al MembershipProvider.ResetPassword método del proveedor de pertenencia al que hace ProviderName referencia la propiedad para restablecer la contraseña del usuario de pertenencia a una nueva contraseña generada automáticamente.ResetPassword calls the MembershipProvider.ResetPassword method of the membership provider referenced by the ProviderName property to reset the password for the membership user to a new, automatically generated password. La nueva contraseña se devuelve al autor de la llamada.The new password is then returned to the caller.

Si EnablePasswordReset esfalse, el proveedor de pertenencia devolverá una excepción.If EnablePasswordReset is false, the membership provider will return an exception.

Si RequiresQuestionAndAnswer null es false, puede proporcionar ResetPassword el answer parámetro o utilizar la sobrecarga que no toma ningún parámetro.If RequiresQuestionAndAnswer is false, you can supply null for the answer parameter, or use the ResetPassword overload that does not take any parameters.

Si se requiere una respuesta de contraseña y se proporciona una respuesta de contraseña incorrecta MembershipPasswordException , el proveedor de pertenencia produce una.If a password answer is required and an incorrect password answer is supplied, a MembershipPasswordException is thrown by the membership provider.

Consulte también:

Se aplica a