2008-10-29 17 views
22

Estoy escribiendo una aplicación web que usa la autenticación de Windows y felizmente puedo obtener el nombre de inicio de sesión del usuario usando algo como:¿Cómo encuentro el nombre para mostrar de Active Directory en una aplicación web de C#?

string login = User.Identity.Name.ToString(); 

pero no necesitan su nombre de usuario Quiero su DisplayName. Me he estado golpeando la cabeza por un par de horas ...

¿Puedo acceder a la AD de mi organización a través de una aplicación web?

Respuesta

29

¿Qué tal esto:

private static string GetFullName() 
    { 
     try 
     { 
      DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName); 
      return de.Properties["fullName"].Value.ToString(); 
     } 
     catch { return null; } 
    } 
+0

Esta es la mejor manera de hacerlo para propretidades de usuario único. – thismat

+0

Sí, me gusta la simplicidad de este MUCHO, especialmente porque funciona. ¡Te debo una bebida! – inspite

+0

Esto funcionó, pero las propiedades de WINNT: // son mucho menos comprensivas que las propiedades de LDAP: // (ver http://www.rlmueller.net/Name_Attributes.htm) así que mientras esto funcionó, no pude obtener direcciones de correo electrónico del usuario utilizando el enlace WINNT: // – inspite

8

Ver pregunta relacionada: Active Directory: Retrieve User information

Consulte también: Howto: (Almost) Everything In Active Directory via C# y más concretamente en la sección "Enumerate an object's properties".

Si usted tiene un camino para conectarse a un grupo en un dominio, el siguiente fragmento de código puede ser útil:

GetUserProperty("<myaccount>", "DisplayName"); 

public static string GetUserProperty(string accountName, string propertyName) 
{ 
    DirectoryEntry entry = new DirectoryEntry(); 
    // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..." 
    entry.Path = "LDAP://..."; 
    entry.AuthenticationType = AuthenticationTypes.Secure; 

    DirectorySearcher search = new DirectorySearcher(entry); 
    search.Filter = "(SAMAccountName=" + accountName + ")"; 
    search.PropertiesToLoad.Add(propertyName); 

    SearchResultCollection results = search.FindAll(); 
    if (results != null && results.Count > 0) 
    { 
     return results[0].Properties[propertyName][0].ToString(); 
    } 
    else 
    { 
      return "Unknown User"; 
    } 
} 
2

hay un proyecto CodePlex para Linq to AD si estás interesado

También se cubre en el libro LINQ Unleashed for C# por Paul Kimmel - utiliza el proyecto anterior como punto de partida.

no afiliado con cualquiera de las fuentes - Acabo de leer el libro recientemente

3

En caso de que alguien se preocupa Me las arreglé para romper éste:

 /// 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=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..." 


     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 results) 
      { 
       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; 
     } 
    } 
+0

este código me salvó el día. !!!! –

4

Utilice esta:

string displayName = UserPrincipal.Current.DisplayName;

Cuestiones relacionadas