1

I'm trying to change the AD password of all members in my system, but my code only changes the password for some members successfully. For members whose password can't be changed, it shows the following error:

System.NullReferenceException: Object reference not set to an instance of an object. at changep1.changep2.changeUserPassword(String _userID, String _oldPassword, String _newPassword) in C:\Users\Intern\source\repos\changep1\changep1\changep2.aspx.cs:line 52

Here is my c# code:

 public string changeUserPassword(string _userID, string _oldPassword, string _newPassword)
        {
            string message="";
            try
            {
                PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "extra.sales-comm.local", "DC=sales-comm,DC=local",
                ContextOptions.SimpleBind, @"admin", "Passw@rd");
                UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, _userID);

                oUserPrincipal.ChangePassword(_oldPassword, _newPassword);


                oUserPrincipal.Save();
            }
            catch (Exception e)
            {
                message = e.ToString();
            }
            return message;
        }

I don't understand why my code doesn't change passwords for all AD members. Please help thanks.

4

1 回答 1

0

您的代码需要在查找身份时检查 UserPrincipal 值是否为空,以防找不到传递的用户 ID。您没有在代码中检查相同的内容。这看起来像是给出空指针异常的原因。

阅读方法UserPrincipal.FindByIdentity Method (PrincipalContext, String)的文档:

返回与指定标识值匹配的用户主体对象。

参数

上下文类型:System.DirectoryServices.AccountManagement.PrincipalContext

PrincipalContext,指定对其执行操作的服务器或域。

identityValue 类型:System.String

用户主体的身份。此参数可以是 IdentityType 枚举中包含的任何格式。


... // IdentityType 枚举成员如下:

会员名称----------- 说明

DistinguishedName---------- 身份是一个专有名称 (DN)。

Guid ---------------------- 标识是一个全局唯一标识符 (GUID)。

Name ---------------- 身份是一个名字。

SamAccountName--------------- 身份是安全帐户管理器 (SAM) 名称。

Sid ------------- 身份是安全描述符定义语言 (SDDL) 格式的安全标识符 (SID)。

UserPrincipalName 身份是用户主体名称 (UPN)。

如下图所示:

         try
            {
                PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "extra.sales-comm.local", "DC=sales-comm,DC=local", ContextOptions.SimpleBind, @"admin", "Passw@rd");
                UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, _userID);
               if ( null != oUserPrincipal){
                oUserPrincipal.ChangePassword(_oldPassword, _newPassword);    
                oUserPrincipal.Save();
               }
               else {
               // return the message that the user-id could not be found.
               // preferably passed argumnet in user-id should be **SamAccountName**
               // please make sure that the user-id corresponds to the members mentioned above
               }
            }
            catch (Exception e)
            {
                message = e.ToString();
            }
于 2018-02-06T08:16:51.347 回答