简体   繁体   English

如何使用 Active Directory 从属性中检索值?

[英]How do I retrieve a value from a property using Active Directory?

I'm trying to write a code that retrieves a user's email from the LDAP server.我正在尝试编写一个从 LDAP 服务器检索用户电子邮件的代码。 The user's email is in the 'mail' property, however, everytime I run it, the email returns "System.DirectoryServices.ResultPropertyValueCollection" instead of the user's email.用户的电子邮件位于“邮件”属性中,但是,每次我运行它时,电子邮件都会返回“System.DirectoryServices.ResultPropertyValueCollection”而不是用户的电子邮件。 Here is my code:这是我的代码:

using (HostingEnvironment.Impersonate())
        {        
            string server = "hello.world.com:389";
            string email = null;

            DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + server + "/DC=hello,DC=world,DC=com");
            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.SearchScope = SearchScope.Subtree;
            dSearch.Filter = "(&(objectClass=users)(cn=" + lanID + "))";
            dSearch.PropertiesToLoad.Add("mail");

            SearchResult result = dSearch.FindOne();

            if (result != null)
            {
                email = result.Properties["mail"].ToString();
                return email;
            }
            else return email = null;
        }

The code takes a user's employee id (lanID) and returns that userID's email (the value under 'mail' property).该代码获取用户的员工 ID (lanID) 并返回该用户 ID 的电子邮件(“邮件”属性下的值)。 How should I do so I don't get System.DirectoryServices.ResultPropertyValueCollection but an actual email?我应该怎么做才能收到 System.DirectoryServices.ResultPropertyValueCollection 而是实际的电子邮件?

You need to use SearchResult.GetDirectoryEntry() Method to get the directory entry which corresponds to this SearchResult.您需要使用SearchResult.GetDirectoryEntry()方法来获取与此 SearchResult 对应的目录条目。

Retrieves the DirectoryEntry that corresponds to the SearchResult from the Active Directory Domain Services hierarchy.从 Active Directory 域服务层次结构中检索与 SearchResult 对应的 DirectoryEntry。 Use GetDirectoryEntry when you want to look at the live entry instead of the entry that was returned through DirectorySearcher, or when you want to invoke a method on the object that was returned.当您要查看实时条目而不是通过 DirectorySearcher 返回的条目时,或者要在返回的对象上调用方法时,请使用 GetDirectoryEntry
--emphasis mine. ——强调我的。

Use the below code:使用以下代码:

DirectoryEntry user = result.GetDirectoryEntry();
string distinguishedName = user.Properties["mail"].Value.ToString();

用这个:

(String)user.Properties["mail"][0];

This means you are trying to convert an entire object to a string.这意味着您正在尝试将整个对象转换为字符串。

Change改变

email = result.Properties["mail"].ToString();

To this对此

email = result.Properties["mail"].Value.ToString();

这个:

email = result.getdirectoryentry.properties("mail").value 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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