我正在使用.NET的System.DirectoryServices.AccountManagement命名空间进行一些Active Directory工作.我注意到这个Principal实现IDisposable,因为该命名空间中的所有东西都继承了,所以会引起一些麻烦Principal.
例如,考虑以下代码来获取组中的所有用户:
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity(domain, "MyGroup");
PrincipalSearchResult<Principal> users = group.GetMembers();
Run Code Online (Sandbox Code Playgroud)
该代码段中的每个类型都会实现IDisposable,包括搜索返回的所有用户以及搜索结果集本身.
处理domain和group物体并不是什么大不了的事(用using()块来容易),但我对每一个结果怎么办?我是否真的必须遍历该users集合并处理每一个?
我对 UserPrincipal 类进行扩展以检索我需要的一些缺失的属性:
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
class UserPrincipalExt : UserPrincipal
{
public UserPrincipalExt(PrincipalContext context)
: base(context)
{
}
[DirectoryProperty("department")]
public string Department
{
get
{
if (ExtensionGet("department").Length != 1)
return null;
return (string)ExtensionGet("department")[0];
}
set
{
this.ExtensionSet("department", value);
}
}
[DirectoryProperty("company")]
public string Company
{
get
{
if (ExtensionGet("company").Length != 1)
return null;
return (string)ExtensionGet("company")[0];
}
set
{
this.ExtensionSet("company", value);
}
}
[DirectoryProperty("c")]
public string CountryAbbreviation
{
get
{
if (ExtensionGet("c").Length != 1)
return null;
return (string)ExtensionGet("c")[0];
}
set
{
this.ExtensionSet("c", …Run Code Online (Sandbox Code Playgroud) c# active-directory userprincipal principalsearcher groupprincipal
我System.DirectoryServices.AccountManagement用来查询用户,然后找到该用户的组.
var _principalContext = new PrincipalContext(ContextType.Domain, domainAddress, adContainer, adQueryAccount, adQueryAccountPassword);
var user = UserPrincipal.FindByIdentity(_principalContext, IdentityType.SamAccountName, account);
var userGroups = user.GetGroups();
foreach (var group in userGroups.Cast<GroupPrincipal>())
{
//////////////////////////////////////////////////////
// getting the underlying DirectoryEntry shown
// to demonstrate that I can retrieve the underlying
// properties without the exception being thrown
DirectoryEntry directoryEntry = group.GetUnderlyingObject() as DirectoryEntry;
var displayName = directoryEntry.Properties["displayName"];
if (displayName != null && displayName.Value != null)
Console.WriteLine(displayName.Value);
//////////////////////////////////////////////////////
Console.WriteLine(group.DisplayName);// exception thrown here...
}
Run Code Online (Sandbox Code Playgroud)
我可以获取底层DirectoryEntry对象并转储其属性和值,但只要GroupPrincipal.DisplayName …
我想使用 Windows 身份验证并获取用户信息,例如名字、姓氏等。我UserPrincipal.Current在 IIS 中使用,但出现异常,但 IIS Express 看起来不错。