如何检查用户在Active Directory中是否存在。 我们将emailId作为用户名传递给方法参数,它是GET方法。
我们已经编写了此方法,但无法正常工作。
[HttpGet("GetADUsers")]
public List<string> GetADUsers(string userName)
{
var domainUsers = new List<string>();
try
{
string domainName = _domainSettings.Value.DomainName;
string domainUserName = _domainSettings.Value.UserName;
string domainPassword = _domainSettings.Value.Password;
PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, domainUserName, domainPassword, ContextOptions.SimpleBind.ToString());
UserPrincipal principalUser = new UserPrincipal(pc);
using (var search = new PrincipalSearcher(principalUser))
{
foreach (var user in search.FindAll().Where(x => x.DisplayName == userName))
{
if (user.DisplayName != null)
{
domainUsers.Add(user.DisplayName);
}
}
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
return domainUsers;
}
答案 0 :(得分:2)
在创建PrincipalContext
之后,您可以调用UserPrincipal.FindByIdentity()
-如果找到了用户,则返回UserPrincipal
-否则为空。
[HttpGet("GetADUsers")]
public bool ADUserExists(string userName)
{
string domainName = _domainSettings.Value.DomainName;
string domainUserName = _domainSettings.Value.UserName;
string domainPassword = _domainSettings.Value.Password;
PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, domainUserName, domainPassword, ContextOptions.SimpleBind.ToString());
UserPrincipal principalUser = UserPrincipal.FindByIdentity(pc, userName);
if (principalUser != null)
{
// gefunden ....
return true;
}
else
{
// nicht gefunden
return false;
}
}