我已成功使用 AccountManagement 代码检索基本 AD 信息,但它仅返回有关返回对象的非常有限的信息集。如何使用 AccountManagement 功能从 AD 获取扩展信息。具体来说,是我的 AD 实例中的职位名称或头衔。
我知道如何使用旧的 DirectoryServices 来做到这一点,但我想知道如何使用新的命名空间来做到这一点。
最佳答案
是的,UserPrincipal
上的默认属性集非常有限 - 但最重要的是:有一个简洁的可扩展性故事!
您需要定义一个从 UserPrincipal
派生的类,然后您可以根据需要轻松访问更多属性。
骨架看起来像这样:
namespace ADExtended
{
[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("User")]
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)
{}
UserPrincipalExSearchFilter searchFilter;
new public UserPrincipalExSearchFilter AdvancedSearchFilter
{
get
{
if (null == searchFilter)
searchFilter = new UserPrincipalExSearchFilter(this);
return searchFilter;
}
}
// Create the "Title" property.
[DirectoryProperty("title")]
public string Title
{
get
{
if (ExtensionGet("title").Length != 1)
return string.Empty;
return (string)ExtensionGet("title")[0];
}
set { ExtensionSet("title", value); }
}
// Implement the overloaded search method FindByIdentity.
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);
}
}
}
这几乎就是全部了! ExtensionGet
和 ExtensionSet
方法允许您“深入”底层目录条目并获取您可能感兴趣的所有属性......
现在,在您的代码中,使用新的 UserPrincipalEx
类而不是 UserPrincipal
:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// Search the directory for the new object.
UserPrincipalEx myUser = UserPrincipalEx.FindByIdentity(ctx, "someUserName");
if(myUser != null)
{
// get the title which is now available on your "myUser" object!
string title = myUser.Title;
}
}
在此处阅读有关 System.DirectoryServices.AccountManagement
命名空间及其可扩展性的所有内容:
更新:抱歉 - 这是 UserPrincipalExSearchFilter
类 - 错过了原始帖子中的那个类。它只是显示了扩展搜索过滤器的能力(如果需要):
public class UserPrincipalExSearchFilter : AdvancedFilters
{
public UserPrincipalExSearchFilter(Principal p) : base(p) { }
public void LogonCount(int value, MatchType mt)
{
this.AdvancedFilterSet("LogonCount", value, typeof(int), mt);
}
}
关于c#-4.0 - 使用 System.DirectoryServices.AccountManagement 获取职位名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9540436/