0

I am using SharePoint 2010, and I can't seem to get this code to return anything in our production environment. The server is set up for Claims Based Authentication.

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 "";
}
4

1 回答 1

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 "";
    }
于 2013-10-24T00:21:26.957 回答