繁体   English   中英

在Framework 4.5中获取活动目录用户属性

[英]Get active directory user attributes in Framework 4.5

我有一个从特定组吸引用户的代码。

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
        GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);

        if (grp != null)
        {
            foreach (Principal p in grp.GetMembers(true))
            {
                Console.WriteLine(p.Name);
            }
        }

问题是我无法获得用户手机,家庭电话,部门,国家/地区。 有人知道如何使用这种方法吗?

尝试在foreach循环中声明UserPrincipal而不是Principal ,以允许您使用专门为Active Directory用户定义的属性。

或者,您可以尝试在循环中包含此代码。

Console.WriteLine(p.ExtensionGet("mobile")); // Mobile Phone
Console.WriteLine(p.ExtensionGet("homePhone"));  // Home Phone
Console.WriteLine(p.ExtensionGet("department"));  // Department
Console.WriteLine(p.ExtensionGet("co")); // Country

ExtensionGet方法使您不仅可以从标准Active Directory字段中检索数据,还可以从目录中包括的其他自定义数据中检索数据。

@HuroSwords答案中的ExtensionGet方法不能直接使用,因为它是受保护的方法。

正如在其他地方提到的,您需要创建自己的子类才能使用它。 我提供了过去所做的示例,以便在下面获得更多用户属性。

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("User")]
public class UserPrincipalExtended : UserPrincipal
{
    public UserPrincipalExtended(PrincipalContext context) : base(context)
    {
    }

    // Implement the overloaded search method FindByIdentity to return my extended type
    public static new UserPrincipalExtended FindByIdentity(PrincipalContext context, string identityValue)
    {
        return (UserPrincipalExtended)FindByIdentityWithType(context, typeof(UserPrincipalExtended), identityValue);
    }

    // Implement the overloaded search method FindByIdentity to return my extended type
    public static new UserPrincipalExtended FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
    {
        return (UserPrincipalExtended)FindByIdentityWithType(context, typeof(UserPrincipalExtended), identityType, identityValue);
    }

    [DirectoryProperty("physicalDeliveryOfficeName")]
    public string Department
    {
        get
        {
            if (ExtensionGet("physicalDeliveryOfficeName").Length != 1)
                return null;
            return (string)ExtensionGet("physicalDeliveryOfficeName")[0];
        }
    }
}

然后像使用普通UserPrincipal对象一样使用子类。

var domain = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipalExtended.FindByIdentity(domain, HttpContext.Current.User.Identity.Name);
Console.WriteLine(userPrincipal.Location);

在您的情况下,您可能需要重新获取主体。

暂无
暂无

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

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