与 AD 的连接在 IIS 中工作正常但在 VS 中不工作

Connection to AD works fine in IIS but not in VS

我正在使用以下代码检查 AD 中是否存在用户名,当我在 VS 中调试应用程序时它抛出 "The username or password is incorrect" 异常但如果我在 IIS 中发布完全相同的代码它工作正常, 按预期返回 true 或 false

private bool UserExist(string path, string username)
        {
            DirectoryEntry entry = new DirectoryEntry(path);
            try
            {
                object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + username + ")";
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }
                else
                {
                    return true;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

这可能意味着用于访问该域的凭据在该域上不受信任。

当使用 ApplicationPoolIdentity 时,它作为计算机进行身份验证。因此,只要该计算机的域在两个域中都受信任,那么它就可以在两个域中工作。

当您使用 IIS Express 在 Visual Studio 中进行调试时,它 运行 在您自己的凭据下。如果它适用于一个域而不适用于另一个域,则意味着您的用户帐户在一个域上不受信任。

你有两个选择:

  1. 更改您的代码以在 DirectoryEntry 的构造函数中传递正确的凭据,具体取决于您需要连接到的域,或者

  2. 如果您的计算机与您所说的计算机在同一个域中,那么请在您的计算机上安装完整的 IIS(不是 IIS Express),在 IIS 中设置站点,然后 setup Visual Studio to debug the app in IIS.这样,调试时它就不会 运行 在您的凭据下。