简体   繁体   中英

Error while getting Active Directory domain name for users using C#.net on Dev Server (Works fine in local)?

I have a method that returns the list for the users and trying to get the fullname based on the domainid. So that i want to populate this list to the Dropdown.

The below code works fine in the local and is throwing exception on the DevBox that "object reference not set ..." at the below line.

UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), stringArray[x]).Name;

Anyone has any solution?

public static List<SelectListItem> GetUsers()
    {
        try 
        { 
            //Get Users list 
            string usersList = “nraja01,sdaniel01,mmontgo01”;
            char[] charArray = new char[] { ',' };
            string[] stringArray = usersList.Split(charArray);

            List<SelectListItem> users = new List<SelectListItem>();
            var user = new SelectListItem(); 

            //loop through each user
            for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
            {
                user = new SelectListItem();
                user.Value = stringArray[x];
                user.Text = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), stringArray[x]).Name;
                users.Add(user);
            }
            return users;
        }
        catch (Exception ex)
        {
            _log.Error("Error occured in GetUsers() method: ", ex);
            return null;
        }
    }

Because of a bug in .NET 4.0, you have to use a different constructor for the PrincipalContext when you are using ContextType.Domain . Use this constructor:

PrincipalContext(ContextType, string)

For example:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName)

See these links for details on the bug:

http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/4c9fea6c-1d0a-4733-a8ac-e3b78d10e999

http://connect.microsoft.com/VisualStudio/feedback/details/610995/unknown-principaloperationexception-when-add-userprincipal-in-collection-groupprincipal-members

我已经设法通过使用它来检索用户的全名。

System.DirectoryServices.AccountManagement.UserPrincipal.Current.GivenName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM