Get current user's email

-1

I've developed an application, but I want to get the current user's email (because of aesthetic and requirements issues).

I can only get the name of the user through the following code:

@HttpContext.Current.User.Identity.Name

How to get the email?

    
asked by anonymous 13.12.2018 / 15:59

1 answer

1

Hefty, good afternoon!

Email is usually a user-tethered AD property. Therefore, you should consult the AD to find the same example:

    ActiveDirectoryManager oUser = new ActiveDirectoryManager();
    UserPrincipal userPrincipal = oUser.GetUser(matricula);

After this you will have in your variable userPrincipal the userPrincipal.EmailAddress property

I hope I have helped.

Putting some other implementations you might need:

Use Usings:

using System.DirectoryServices.AccountManagement;
using System.Web.Security;

Constructor and example variables

        /// <summary>
        /// AD Host Adress
        /// </summary>
        private string host;

        /// <summary>
        /// Default OU
        /// </summary>
        private string defaultOU;
        /// <summary>
        /// Usuario do AD para consulta
        /// </summary>
        private string ADUsuario;
        /// <summary>
        /// Senha do user para consulta
        /// </summary>
        private string ADSenha;

public ActiveDirectoryManager()
        {

            //Usuario para acesso AD
            ADUsuario = "UsuariodeRedeAutorizado";
            //Senha para acesso AD
            ADSenha = "senhadoseuusuario";

            host = "seuDominio";
            defaultOU = "OUdasuaempresa";
        }

Here you authenticate to 'AD'

private PrincipalContext GetPrincipalContext()
        {
            return new PrincipalContext(ContextType.Domain, host, defaultOU, ADUsuario, ADSenha);
        }

Here you receive from AD the user infos

public UserPrincipal GetUser(string user)
        {
            UserPrincipal userPrincipal = null;

            using (PrincipalContext principalContext = GetPrincipalContext())
            {
                userPrincipal = UserPrincipal.FindByIdentity(principalContext, user);
            }

            return userPrincipal;
        }
    
13.12.2018 / 16:39