c# - 使用目录服务帐户管理帮助查找用户

标签 c# active-directory directoryservices

我在尝试通过参数 (userName) 将值传递到方法时遇到问题。如果我对值进行硬编码,它将找到用户。

任何指导将不胜感激,

protected void btnSubmit_Click(object sender, EventArgs e)
{
   if (!String.IsNullOrEmpty(txtUserName.Text))
   {
      string userName = txtUserName.ToString();

      PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "car2.local", "DC=car2,DC=local");
      UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName);

      if(usr != null)
      {
         lblStatus.Text = "user exists";
      }
      else
      {
         lblStatus.Text = "user does not exists";
      }
   }
}

最佳答案

试试这个 - 读出文本框的 .Text 属性(并调用 .Trim() 来去除任何额外的、多余的空格)而不是使用 .ToString() 就可以了:

string userName = txtUserName.Text.Trim();

UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, userName);

如果您没有指定要搜索的身份类型 - 那么 AD 将搜索最常见的身份类型并希望找到您的用户!

关于c# - 使用目录服务帐户管理帮助查找用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5539551/

相关文章:

c# - 从 byte[] 转换为字符串

c# - SQLite in 10 UWP App Assertion Error (p->iForeGuard==(int)FOREGUARD);

c# - System.DirectoryServices.DirectorySearcher.PropertiesToLoad 中有哪些不同的可用属性

C# Active Directory 调用非常慢

c# - 如何复制 System.Drawing.Image 值?

c# - 为什么我的坐标 (1,1) 从 (0, 1) 开始?

excel - 如何在 VBA 中管理从 ADsDSOObject 提供程序检索的日期对象?

powershell - 如何根据组扩展属性获取用户所属的所有组

java - 在 Java 的 Active Directory 系统中通过 IP 对用户进行身份验证

asp.net - COMException 未知错误 (0x80005000) - DirectoryServices