2013-10-18 21 views
0

我正在使用SharePoint 2010,而且似乎无法让此代码在我们的生产环境中返回任何内容。服务器设置为基于声明的身份验证。无法使用PrincipalContext在基于声明的身份验证的SharePoint 2010中工作

private string GetADName(string userID) 
{ 
    try 
    { 
     PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

     // define a "query-by-example" principal - here, we search for a UserPrincipal 
     // and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller" 
     UserPrincipal qbeUser = new UserPrincipal(ctx); 
     qbeUser.SamAccountName = userID; 

     // create your principal searcher passing in the QBE principal  
     PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

     // find all matches 
     foreach (var found in srch.FindAll()) 
     { 
      return found.Name; 
     } 
    } 
    catch (Exception ex) 
    { 
     this.lblErrors.Text = ex.Message + "<br />\r\n" + ex.StackTrace; 
    } 
    return ""; 
} 
+0

这是代码暂存环境中工作?如果你传入“*”而不是userID,你会得到结果吗? – Dan

回答

3

我不得不使用HostingEnvironment.Impersonate()

private string GetADName(string userID) 
    { 
     try 
     { 
      using (HostingEnvironment.Impersonate()) 
      { 

       PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

       UserPrincipal qbeUser = new UserPrincipal(ctx); 

       qbeUser.SamAccountName = userID.ToLower(); 

       PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

       foreach (var found in srch.FindAll()) 
       { 
        if (found.SamAccountName.ToLower() == userID.ToLower()) 
        { 
         return found.Name; 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
     } 
     return ""; 
    } 
相关问题