How to: Display the name of the Windows user logged into your ASP.NET Site


This is really pretty simple but I was surprised not to find it in any one blog posting. It's easy to display the Application Pool account rather than the logged in user. Some articles said to turn on Impersonation, but that's often a bad idea for other reasons. This is what worked for me just now:

string username = "";
IPrincipal
userIdentity = HttpContext.Current.User;
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal =
       
UserPrincipal.FindByIdentity(context, userIdentity.Identity.Name);
if (userPrincipal != null)
{
        username = userPrincipal.DisplayName;
}

I hope this helps someone; thanks!

 

Comments (0)

Skip to main content