How can I check the user is exist or not in Active Directory. we are passing emailId as userName to the method parameter and it is GET method.
We have written this method, but it is not working properly.
[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;
}
userNameto theDisplayName. You should probably be comparing it to theSamAccountNameproperty, which is the username in AD. But the answer by marc_s will likely be a faster search anyway.