Active Directory搜索会抛出异常并搜索无效的名称

时间:2017-07-10 12:59:24

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

我正在使用asp.NET MVC5网站对Active Directory中的用户进行研究。当我进行无效搜索时(例如''éééézztaaz'),ArgumentException不断被抛出,但我不明白。这是我的搜索方法:

public List<ADProperties> SearchUserByName(string name)
{
    //ADProperties is a POCO to store values retrieved
    try
    {

        List<ADProperties> theListIWant = new List<ADProperties>();
        //createDirectoryEntry() is a method to establish a connection to Active Directory
        DirectoryEntry ldapConnection = createDirectoryEntry();
        DirectorySearcher search = new DirectorySearcher(ldapConnection);

        //Search filter to find users
        search.Filter = "(&(objectClass=user)(anr=" + name + "))";

        ///Properties to load
        search.PropertiesToLoad.Add("objectSID");
        search.PropertiesToLoad.Add("displayName");
        search.PropertiesToLoad.Add("distinguishedName");
        resultCollection = search.FindAll();

        //ArgumentException at if statement
        //I put this to AVOID exceptions, then in my controller, if value is null 
        //I return a different view
        if (resultCollection==null ||resultCollection.Count==0)
        {
            return null;
        }

     }
     else
     { //Do stuff and return
          return theListIWant;
    }catch(ActiveDirectoryOperationException e)
    {
        Console.WriteLine("Active Directory Operation Exception caught: " + e.ToString());
    }
    return null;
}

确切的例外是:

  

搜索过滤器(&amp;(objectClass = user)(anr =))无效

(翻译自法语)

所以我没理解。我添加了条件以避免抛出异常,但显然它没有帮助。

1 个答案:

答案 0 :(得分:1)

我建议改变:

if (resultCollection==null ||resultCollection.Count==0)
{
    return null;
}

为:

try
{
    if (resultCollection == null || resultCollection.Count == 0)
    {
        return null;
    }
}
catch (ArgumentException)
{
    return null;
}

这将确保如果抛出ArgumentException,它将被视为与resultCollection为空的方式相同。