【问题标题】:How to get user details from different domain 'System.Runtime.InteropServices.COMException'如何从不同域“System.Runtime.InteropServices.COMException”获取用户详细信息
【发布时间】:2014-03-07 12:08:13
【问题描述】:

我正在尝试从不同域获取用户详细信息,但它抛出以下错误:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll but was not handled in user code

代码如下:

// Getting domain
var context = new DirectoryContext(DirectoryContextType.Domain, "alpha");
Domain domain = Domain.GetDomain(context);

using (DirectorySearcher searcher = new DirectorySearcher())
{
    var de = new DirectoryEntry(domain.Name);
    searcher.SearchRoot = de;
    searcher.SearchScope = SearchScope.Subtree;
    searcher.PropertiesToLoad.Add("sAMAccountName");
    searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", "myusername");

    // *** ERROR HERE ***        
    var results = searcher.FindAll();
}

我已经尝试以域管理员身份运行 Visual Studio,但没有成功。

提前致谢。

【问题讨论】:

  • 内部异常中有什么?
  • 您是否尝试从与您连接的域不同的域中读取?您是否尝试在 DirectoryEntry 构造函数中为 DC (LDAP://xxx) 指定完整的 LDAP 字符串?

标签: c# asp.net asp.net-mvc-4 active-directory directorysearcher


【解决方案1】:

以下代码仅在您使用 System.DirectoryServices.ActiveDirectory 添加名称空间并添加引用时才有效。

// Get user name
string userName = User.Identity.Name;
var domainName = username.Split('\\')[0];

// Getting domain
var directoryContext = new DirectoryContext(DirectoryContextType.Domain, domainName);
Domain domain = Domain.GetDomain(directoryContext);

using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain.Name))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName))
    {
        if (user != null)
        {
            // Get details here
            var name = user.GivenName;
        }
    }
}

【讨论】:

  • 对我来说非常完美,直到我到达 PrincipalContext 然后它抛出与问题相同的异常。我正在从不同的域阅读,所以我确定这是问题的一部分。
猜你喜欢
  • 2011-09-01
  • 1970-01-01
  • 2014-11-08
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
相关资源
最近更新 更多