参数

username

为其更新密码的用户。

oldPassword

指定的用户的当前密码。

newPassword

指定的用户的新密码。

返回值

如果密码成功更新,则返回 true。如果提供的旧密码无效,用户被锁定或数据库中不存在该用户,则返回 false

备注

Membership 类调用此方法来更新 ASP.NET 应用程序配置文件 (Web.config) 中指定的 SQL Server 数据库用户的密码。

最大密码长度是 128 个字符。

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

先通过 Membership 类的 Provider 属性获得一个对 SqlMembershipProvider 实例的引用后,可直接调用 ChangePassword 方法。Provider 属性公开应用程序的 Web.config 文件中指定的 defaultProvider。而配置的提供程序则不是使用 Providers 引用的默认提供程序。

还可以通过使用 ChangePassword 方法更改用户密码。

删除所有参数值的前导和尾随空格。

示例

下面的代码示例修改指定用户的密码。

View Code

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<mce:script runat="server"><!--
public void ChangePassword_OnClick(object sender, EventArgs args)
{
  try
  {
    // Update the password.
      //User.Identity.Name = "laozhai";
      if (Membership.Provider.ChangePassword("laozhai", OldPasswordTextbox.Text, PasswordTextbox.Text))
    {
      Msg.Text = "Password changed.";
      return;
    }
  }
  catch
  {
  }

  Msg.Text = "Password change failed. Please re-enter your values and try again.";
}
// --></mce:script>
<html>
<head>
<title>Change Password</title>
</head>
<body>

<form id="Form1" runat="server">
  <h3>Change Password for <%=User.Identity.Name%></h3>

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

  <table CellPadding="3" border="0">
    <tr>
      <td>Old Password:</td>
      <td><asp:Textbox id="OldPasswordTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="OldPasswordRequiredValidator" runat="server"
                                      ControlToValidate="OldPasswordTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordRequiredValidator" runat="server"
                                      ControlToValidate="PasswordTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Confirm Password:</td>
      <td><asp:Textbox id="PasswordConfirmTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordConfirmRequiredValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" 
                                      ErrorMessage="Required" />
          <asp:CompareValidator id="PasswordConfirmCompareValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ControlToCompare="PasswordTextBox"
                                      ErrorMessage="Confirm password must match password." />
      </td>
    </tr>
    <tr>
      <td></td>
      <td><asp:Button id="ChangePasswordButton" Text="Change Password" 
                      OnClick="ChangePassword_OnClick" runat="server" /></td>
    </tr>
  </table>
</form>

</body>
</html>

使用方法:

在已有的项目DNNDEMO中添加一个testChagePwd.aspx文件,然后将上面的代码粘贴过去。

这里测试User.Identity.Name为空,一次我们必须认为将User.Identity.Name = "laozhai";这个参数传进去。

测试修改密码成功。

下面是通过reflector得到的源码

View Code

public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
    int num;
    bool flag;
    SecUtility.CheckParameter(ref username, true, true, true, 0x100, "username");
    SecUtility.CheckParameter(ref oldPassword, true, true, false, 0x80, "oldPassword");
    SecUtility.CheckParameter(ref newPassword, true, true, false, 0x80, "newPassword");
    string salt = null;
    if (!this.CheckPassword(username, oldPassword, false, false, out salt, out num))
    {
        return false;
    }
    if (newPassword.Length < this.MinRequiredPasswordLength)
    {
        throw new ArgumentException(SR.GetString("Password_too_short", new object[] { "newPassword", this.MinRequiredPasswordLength.ToString(CultureInfo.InvariantCulture) }));
    }
    int num3 = 0;
    for (int i = 0; i < newPassword.Length; i++)
    {
        if (!char.IsLetterOrDigit(newPassword, i))
        {
            num3++;
        }
    }
    if (num3 < this.MinRequiredNonAlphanumericCharacters)
    {
        throw new ArgumentException(SR.GetString("Password_need_more_non_alpha_numeric_chars", new object[] { "newPassword", this.MinRequiredNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture) }));
    }
    if ((this.PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(newPassword, this.PasswordStrengthRegularExpression))
    {
        throw new ArgumentException(SR.GetString("Password_does_not_match_regular_expression", new object[] { "newPassword" }));
    }
    string objValue = base.EncodePassword(newPassword, num, salt);
    if (objValue.Length > 0x80)
    {
        throw new ArgumentException(SR.GetString("Membership_password_too_long"), "newPassword");
    }
    ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(username, newPassword, false);
    this.OnValidatingPassword(e);
    if (e.Cancel)
    {
        if (e.FailureInformation != null)
        {
            throw e.FailureInformation;
        }
        throw new ArgumentException(SR.GetString("Membership_Custom_Password_Validation_Failure"), "newPassword");
    }
    try
    {
        SqlConnectionHolder connection = null;
        try
        {
            connection = SqlConnectionHelper.GetConnection(this._sqlConnectionString, true);
            this.CheckSchemaVersion(connection.Connection);
            SqlCommand command = new SqlCommand("dbo.aspnet_Membership_SetPassword", connection.Connection);
            command.CommandTimeout = this.CommandTimeout;
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(this.CreateInputParam("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName));
            command.Parameters.Add(this.CreateInputParam("@UserName", SqlDbType.NVarChar, username));
            command.Parameters.Add(this.CreateInputParam("@NewPassword", SqlDbType.NVarChar, objValue));
            command.Parameters.Add(this.CreateInputParam("@PasswordSalt", SqlDbType.NVarChar, salt));
            command.Parameters.Add(this.CreateInputParam("@PasswordFormat", SqlDbType.Int, num));
            command.Parameters.Add(this.CreateInputParam("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow));
            SqlParameter parameter = new SqlParameter("@ReturnValue", SqlDbType.Int);
            parameter.Direction = ParameterDirection.ReturnValue;
            command.Parameters.Add(parameter);
            command.ExecuteNonQuery();
            int status = (parameter.Value != null) ? ((int) parameter.Value) : -1;
            if (status != 0)
            {
                string exceptionText = this.GetExceptionText(status);
                if (this.IsStatusDueToBadPassword(status))
                {
                    throw new MembershipPasswordException(exceptionText);
                }
                throw new ProviderException(exceptionText);
            }
            flag = true;
        }
        finally
        {
            if (connection != null)
            {
                connection.Close();
                connection = null;
            }
        }
    }
    catch
    {
        throw;
    }
    return flag;
}

 

 

 

作者:xwdreamer