我可以获得Active Directory用户信息,例如电子邮件,电话和电话;经理使用UserPrinciple

时间:2015-01-17 00:51:55

标签: c# asp.net asp.net-mvc-5 userprincipal

我的asp.net mvc5 Web应用程序中包含以下代码: -

List<DomainContext> results = new List<DomainContext>();
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                var searchResults = searcher.FindAll();



                foreach (Principal p in searchResults)
                {
                  {
                    DomainContext dc = new DomainContext();
                    dc.DisplayName = p.DisplayName;
                    dc.UserPrincipalName = p.UserPrincipalName;
                    dc.Name = p.Name;
                    dc.SamAccountName = p.SamAccountName ;
                    dc.DistinguishedName =     p.DistinguishedName;

                    results.Add(dc);

我可以获取这些AD信息,例如显示名称,名称等,但我也可以使用上面的代码获取这些信息: -

  • 电子邮件地址。
  • 电话。
  • 管理器

感谢?

2 个答案:

答案 0 :(得分:1)

您需要用户名,第一个,最后一个和smtp。 如果你有,请输入以下代码:

var adService = new DirectorySearcher(new DirectoryEntry());
    adService.Filter = "(&(objectClass=user)(anr=LOGON))";
    adService.PropertiesToLoad.Add("FirstName");
    adService.PropertiesToLoad.Add("LastName");
    adService.PropertiesToLoad.Add("SMTP");
    return adService.FindOne();

答案 1 :(得分:1)

下面我已更新您现有的代码以使用UserPrincipal。

List<UserPrincipal> results = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                var searchResults = searcher.FindAll();
                foreach (Principal p in searchResults)
                {
                  {
                    UserPrincipal userPrincipal = p as UserPrincipal;
                    if (userPrincipal != null)
                        results.Add(userPrincipal);

在这里,我添加了代码,向您展示如何在更高级别获得所需的其他属性。

//Get information you need from UserPrincipal..
var matchingUsers = results.Where(p => p.DisplayName.ToLower() == "bob");
foreach (var matchedUser in matchingUsers)
{   
  string telephone = matchedUser.VoiceTelephoneNumber;
  string email = matchedUser.EmailAddress;
  var directoryEntry = matchedUser.GetUNderlyingObject() as DirectoryEntry;
  string manager = directoryEntry.Properties["manager"] as string;
}