我从我们的网络团队成员那里得到了这个:
可以看到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
等。
在这里阅读所有相关内容:
- Managing Directory Security Principals in the .NET Framework 3.5
- MSDN docs on System.DirectoryServices.AccountManagement
基本上,您只需定义一个基于 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/