2017-07-10 50 views
0

我正在使用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; 
} 

確切的例外是:

的搜索過濾器(&(objectClass的=用戶)(ANR =))無效

(譯自法語)

因此我不沒有得到它。我添加了條件以避免拋出異常,但顯然它沒有幫助。

回答

1

我建議改變:

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

到:

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

這將確保如果ArgumentException被拋出,這將被視爲相同的方式,如果resultCollection爲空。

+0

是的,是有道理的,例外的全部點,所以謝謝! –