How to Show User Name of Currently Logged User?
If you use ASP.NET membership on your site, common practice is to display current user's user name on page once he or she is logged in. Here is the code that display welcome message to current user:
[ C# ]
protected void Page_Load(object sender, EventArgs e)
{
// First find if user is logged in
if (Context.User.Identity.IsAuthenticated)
{
// Finds user name and says Hi
lblWelcome.Text = "Hi " + Context.User.Identity.Name;
}
else
{
// It is anonymous user, say hi to guest
lblWelcome.Text = "Hi guest";
}
}
[ VB.NET ]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Find if user is logged in
If (Context.User.Identity.IsAuthenticated) Then
' Finds user name and says Hi
lblWelcome.Text = "Hi " + Context.User.Identity.Name
Else
' It is anonymous user, say hi to guest
lblWelcome.Text = "Hi guest"
End If
End Sub
Another option to find user name is to use Membership.GetUser().UserName property instead of Context.User.Identity.Name.
Showing current user name in LoginView control
LoginView control can show different templates for logged and anonymous user without need to write server side code. There are <LoggedInTemplate> and <AnonymousTemplate> templates that make this task easier. Next markup code shows two different templates. If user is authenticated, control will display <LoggedInTemplate>, shows current user name and button Logout. If user is not authenticated, LoginView control will display <AnonymousTemplate>, and shows "Hi guest" message with links to Login.aspx and Register.aspx pages:
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
Hi <%= Context.User.Identity.Name %>
<asp:Button ID="btnLogout" runat="server" Text="Logout"
onclick="btnLogout_Click" />
</LoggedInTemplate>
<AnonymousTemplate>
Hi Guest
<a href="/Login.aspx">Login</a>
<a href="/Register.aspx">Register</a>
</AnonymousTemplate>
</asp:LoginView>
Related articles:
1. How To Change User's Email In ASP.NET Membership?
2. How to Find If User Is Logged In?