Jem*_*Jem 5 c# account-management asp.net-4.0
我已经实现了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);
Run Code Online (Sandbox Code Playgroud)
我一直在寻找,似乎无法找到答案,以确认这是否可以做到.如果我不能使用AccountManagement,那么获得sAMAccountName给employeeID的最佳方法是什么?
小智 11
您不需要超出System.DirectoryServices.AccountManagement命名空间.
UserPrincipal searchTemplate = new UserPrincipal(adAuth);
searchTemplate.EmployeeID = "employeeID";
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
UserPrincipal user = (UserPrincipal)ps.FindOne();
Run Code Online (Sandbox Code Playgroud)
在此示例中,如果未找到用户,则用户对象将为null.如果要查找UserPrinicipal对象的集合,可以在PrincipalSearcher(ps)对象上使用FindAll方法.
另请注意,FindOne方法返回一个Principal对象,但我们知道它实际上是一个UserPrincipal,因为UserPrincipal是搜索过滤器的一部分,所以应该这样处理(转换).