Displaying Current User Information in WSS v3
Here’s a tip that’s really simple but I had a number of people ask me about it at TechEd so I thought I’d post it here. Apparently it’s a common requirement to display user information, such as name, login name, or email address on various master and layout pages throughout a site. Although the Welcome/Login control at the top of the page shows the name of the currently logged in user, either people are removing this control or simply need the information duplicated elsewhere on the page.
In 2003, this was a challenge as the SafeMode Parser would block all attempts to include inline code blocks on site definition pages – we had to get creative with server and user controls to make it happen. In 2007, this is no longer the case. Inline code can be inserted into any master or layout page as required, giving designers and developers an easy way to expose object model functionality without writing and deploying compiled assemblies.
One of the easiest to use methods for displaying basic information is the ‘SPContext’ class, which replaces the old and cumbersome ‘SPControl.GetContextWeb(Context)’ method. User information is accessible via the CurrentUser property of the SPWeb class, which is exposed using the following syntax:
< % = SPContext.Current.Web.CurrentUser % >
There are a number of properties for CurrentUser, including Name (just like it sounds, the user’s name), Login Name (user ID), and Email (users’s email address). Displaying each of these properties is as easy as:
< % = SPContext.Current.Web.CurrentUser.Name % >
< % = SPContext.Current.Web.CurrentUser.LoginName % >
< % = SPContext.Current.Web.CurrentUser.Email % >
These methods can also be used to access the current user’s group membership, roles, alerts and various other properties. Be advised that there are a few issues with these methods to be aware of. For example, if you’re using forms-based authentication, the LoginName property will return the user ID in the format ‘<authenticationprovidername>:<userid>’ (for normal NTLM authentication, it will return ‘DOMAIN\<userid>’). Also, it’s always a good idea to wrap any inline code in ‘try…catch’ blocks as an untrapped error will prevent the entire page from loading.