当前位置:  开发笔记 > 编程语言 > 正文

.NET:如何在Active Directory中查找用户?

如何解决《.NET:如何在ActiveDirectory中查找用户?》经验,为你挑选了1个好方法。

如何在Active Directory中查找用户?

一些示例用户名是:

avatopia \伊恩

化身\伊恩

ian@avatopia.com

ian@avatopia.local

avatopia.com \伊恩

重要的是要注意我不知道域的名称,我不应该硬编码.

堆栈溢出上有一些示例代码失败.

using System.DirectoryServices;

/// 
/// Gets the email address, if defined, of a user from Active Directory.
/// 
/// The userid of the user in question.  Make
/// sure the domain has been stripped first!
/// A string containing the user's email address, or null
/// if one was not defined or found.
public static string GetEmail(string userid)
{
    DirectorySearcher searcher;
    SearchResult result;
    string email;

    // Check first if there is a slash in the userid
    // If there is, domain has not been stripped
    if (!userid.Contains("\\"))
    {
        searcher = new DirectorySearcher();
        searcher.Filter = String.Format("(SAMAccountName={0})", userid);
        searcher.PropertiesToLoad.Add("mail");
        result = searcher.FindOne();
        if (result != null)
        {
            email = result.Properties["mail"][0].ToString();
        }
    }

    return email;
}

它特别确保您没有传递完整的用户名.例如

Bad: avatopia\ian
Bad: avatar\ian
Good: ian
Good: ian

由于您不允许通过域,因此无法区分这两个用户

ian
ian

另一个人在sackoverflow上有同样的问题,但接受的答案说你必须

首先找到所需域的命名上下文

我不知道 "命名上下文"是什么,我不知道"必需的域名"是什么.我真的不想写一个正则表达式来尝试将用户名解析为域名和帐户名,例如

domain.something\user-name

domain.something
user-name

因为我知道会有一些边缘情况我会出错.我想要在Active Directory中查找用户的正确,有意的方法.

CodeProject上有一个很好的页面如何在Active Directory中执行几乎所有操作,但是您无法通过用户名查找用户的信息

我希望我可以给我的域控制器(无论是谁,无论它在哪里,无论它叫什么)一个用户名,它将找出用户所属的域,与该域控制器通信,并完成工作.



1> inspite..:

这适合我.

您应该能够区分不同域控制器上的不同用户(即域/用户名),因为ldappaths会有所不同.根据你的意思,你不在乎,因为你没有指定ldappath.

您正在就剥离User.Identity.Name的域名进行出价交易.但是我不确定你担心的是什么,你只需要把弦切成两半,第一次遇到'\'时就要砍掉了.

如果您不喜欢,可以使用"正确的方法":http://msdn.microsoft.com/en-us/library/ms973834.aspx

这也很好 http://geekswithblogs.net/mhamilton/archive/2005/09/30/55621.aspx

      /// This is some imaginary code to show you how to use it

      Session["USER"] = User.Identity.Name.ToString();
      Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D
      string ldappath = "LDAP://your_ldap_path";
      // "LDAP://CN=, CN =, DC=, DC=,..."


      Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn");
      Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName");
      Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail");
      Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName");
      Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn");


/// working code

public static string GetAttribute(string ldappath, string sAMAccountName, string attribute)
    {
        string OUT = string.Empty;

        try
        {
            DirectoryEntry de = new DirectoryEntry(ldappath);
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))";

            SearchResultCollection results = ds.FindAll();

            foreach (SearchResult result in ds.FindAll())
            {
                OUT =  GetProperty(result, attribute);
            }
        }
        catch (Exception t)
        {
            // System.Diagnostics.Debug.WriteLine(t.Message);
        }

        return (OUT != null) ? OUT : string.Empty;
    }

public static string GetProperty(SearchResult searchResult, string PropertyName)
    {
        if (searchResult.Properties.Contains(PropertyName))
        {
            return searchResult.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

对于域/用户名

    public static string GetDomain(string s)
    {
        int stop = s.IndexOf("\\");
        return (stop > -1) ?  s.Substring(0, stop + 1) : null;
    }

    public static string GetLogin(string s)
    {
        int stop = s.IndexOf("\\");
        return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
    }

对于username @ domain style

   public static string GetDomain(string s) //untested
    {
        int stop = s.IndexOf("@");
        return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
    }


    public static string GetLogin(string s) //untested
    {
        int stop = s.IndexOf("@");
        return (stop > -1) ?  s.Substring(0, stop) : null;
    }

推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有