[英]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.