c# - 从 AD 获取扩展属性?

标签 c# active-directory

我从我们的网络团队成员那里得到了这个:

enter image description here

可以看到extensionAttribute2里面有值。我如何检索此值 - 我在 UserPrincipal 对象中看不到 extensionAttributes - 除非我遗漏了什么。

我已经更进一步并尝试了以下内容:

        UserPrincipal myUser = UserPrincipal.FindByIdentity(con, identityName);

        DirectoryEntry de = (myUser.GetUnderlyingObject() as DirectoryEntry);

        if (de != null)
        {
            // go for those attributes and do what you need to do
            if (de.Properties.Contains("extensionAttribute2"))
            {
                return de.Properties["extensionAttribute2"][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

但是这不起作用 - 调试它有大约 40 个可用属性但没有用于 extensionAttribute2

最佳答案

如果您使用的是 .NET 3.5 及更高版本并使用 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间,则可以轻松扩展现有的 UserPrincipal 类以获得更高级的属性,如 Manager 等。

在这里阅读所有相关内容:

基本上,您只需定义一个基于 UserPrincipal 的派生类,然后定义您想要的其他属性:

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx : UserPrincipal
{
    // Inplement the constructor using the base class constructor. 
    public UserPrincipalEx(PrincipalContext context) : base(context)
    { }

    // Implement the constructor with initialization parameters.    
    public UserPrincipalEx(PrincipalContext context,
                         string samAccountName,
                         string password,
                         bool enabled) : base(context, samAccountName, password, enabled)
    {} 

    // Create the "extensionAttribute2" property.    
    [DirectoryProperty("extensionAttribute2")]
    public string ExtensionAttribute2
    {
        get
        {
            if (ExtensionGet("extensionAttribute2").Length != 1)
                return string.Empty;

            return (string)ExtensionGet("extensionAttribute2")[0];
        }
        set { ExtensionSet("extensionAttribute2", value); }
    }
}

现在,您可以在代码中使用 UserPrincipalEx 的“扩展”版本:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // Search the directory for the new object. 
    UserPrincipalEx inetPerson = UserPrincipalEx.FindByIdentity(ctx, IdentityType.SamAccountName, "someuser");

    // you can easily access the ExtensionAttribute2 now
    string department = inetPerson.ExtensionAttribute2;
}        

关于c# - 从 AD 获取扩展属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492883/

相关文章:

c# - 使用 Azure WebJobs 发送不同类型的电子邮件

c# - 索引、IndexMany、IndexAsnyc、IndexManyAsync 与 NEST

c# - 如何使用 LINQ 查找 ResultPropertyCollection 中的任何值是否包含某个子字符串?

java - 使用 Java 创建 Activity 目录用户时遇到问题

ruby-on-rails-3 - 集成 ActiveAdmin 和 adauth

active-directory - 连接到端口 636 时出现 LDAP 连接错误 ("The server is not operational.")

Linux 和 Mac 中的 C#

c# - 插入文件路径

javascript - 为什么我的 ajax 调用无法到达我的 .NET WebMethod?

.net - UserPrincipal 对象中的域名在哪里?