我有一个代码可以从特定的群组中获取用户。
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);
}
}
问题是我无法获得用户手机,家庭电话,部门,国家。有人有任何想法如何使用这种方法吗?
答案 0 :(得分:0)
尝试在UserPrincipal
循环中声明Principal
而不是foreach
,以允许您使用专门为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字段中的数据,还可以检索目录中包含的其他自定义数据。
答案 1 :(得分:0)
@HuroSwords答案中的ExtensionGet方法无法直接使用,因为它是受保护的方法。
如前所述elsewhere,您需要创建自己的子类才能使用它。我已经包含了我过去所做的一些示例,以获取以下额外的用户属性。
[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);
在您的情况下,您可能需要重新获取主体。