通过employeeID获取UserPrincipal

时间:2014-05-28 15:49:43

标签: c# asp.net-4.0 account-management

我已经实现了System.DirectoryServices.AccountManagement用于身份验证到我的webapps查找用户(UserPrincipal)byidentity给定的用户名。但是,我有几种情况需要获得只有employeeID的AD帐户。在AccountManagement中给定一个employeeID,是否有一种获得UserPrincipal(甚至只是sAMAccountName)的好方法?

我目前正在努力通过用户名抓取用户:

PrincipalContext adAuth = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);

//get user
UserPrincipal usr = UserPrincipal.FindByIdentity(adAuth, username);

我一直在寻找,似乎无法找到答案,以确认这是否可以做到。如果我不能使用AccountManagement,那么获得sAMAccountName给employeeID的最佳方法是什么?

2 个答案:

答案 0 :(得分:11)

您不需要超出System.DirectoryServices.AccountManagement命名空间。

UserPrincipal searchTemplate = new UserPrincipal(adAuth);
searchTemplate.EmployeeID = "employeeID";
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal)ps.FindOne();

在此示例中,如果未找到用户,则用户对象将为null。如果要查找UserPrinicipal对象的集合,可以在PrincipalSearcher(ps)对象上使用FindAll方法。

另请注意,FindOne方法返回一个Principal对象,但我们知道它实际上是一个UserPrincipal,因为UserPrincipal是搜索过滤器的一部分,因此应该这样处理(转换)。

答案 1 :(得分:1)

所以,我找到了一种使用System.DirectoryServices的方法,如下所示,但它似乎相当冗长:

string username = "";

DirectoryEntry entry = new DirectoryEntry(_path);

//search for a DirectoryEntry based on employeeID
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(employeeID=" + empID + ")";

//username
search.PropertiesToLoad.Add("sAMAccountName");

SearchResult result = search.FindOne();

//get sAMAccountName property
username = result.Properties["sAMAccountName"][0].ToString();

当然,我可以将其用于其他属性,但我非常喜欢使用AccountManagement的强类型属性。