This article is reposted from my old MSDN blog. Please post comments here as I am no longer able to publish or respond to them on MSDN. Thanks!
This is really pretty simple but I was surprised not to find it in any one blog posting. The following code retrieves the display name of the logged in user, such as “Bob German” (not “domain\username”). It’s easy to accidentally 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!