Get email from current User

Asked

Viewed 33 times

-1

I developed an application, however I want to get the current user email (because aesthetic and requirements issues).

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

@HttpContext.Current.User.Identity.Name

How to get the email?

1 answer

1


Hefty, good afternoon, Hefty!

The email is a property linked to the user’s AD normally. So you should consult the AD to find it, example:

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

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

I hope I’ve helped.

Placing some other implementations you may need:

Use the Usings:

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

Constructor and sample 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 log in to 'AD'

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

Here you get from AD the user’s information

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

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

            return userPrincipal;
        }
  • Thank you for trying to help me, but I’m having doubts about how I’m going to implement this -.-

  • I’ve added a few items for you to take as an example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.