How to: Get the currently logged on user’s Username and ID (ASP.NET – v:3.5+)

There’s very easy and practical way to deal with the need to get a user’s Username and ID when programming in an ASP.NET environment.

Getting the user’s Username is simpler, in the sense that, in order to get a GUID you will need to add both a reference and a “using” statement.

On the other hand, to get the username, you will only need to use an HttpContext request.

Add a reference to: System.DirectoryServices.AccountManagement and a using statement to your code. Having done that, the following piece of code will get the username and ID of the currently logged on user and assign it to local fields.

string currentUserUsername = HttpContext.Current.User.Identity.Name;
Guid currentUserGuid = (Guid)UserPrincipal.Current.Guid;

Do notice that in the case of getting the Guid, you will need to explicitly cast it to Guid.

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.