从AD获取扩展属性?
我是从我们的网络团队成员那里得到的:
您可以看到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
等。
在这里阅读所有相关内容:
- 管理.NET Framework 3.5中的目录安全性主体
- System.DirectoryServices.AccountManagement上的MSDN文档
基本上,您只需基于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; }
使用marc_s使用的代码添加以下内容:
public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue) { return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue); } // Implement the overloaded search method FindByIdentity. public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue); }