Thursday, January 10, 2013

Get Username for logged in user Asp.net

The below is when using Windows Authentication using ASp.net

In ASP.NET, please use User.Identity.Name to get the logon user. User.Identity.Name might be empty if Anonymous Authentication is enabled in IIS.
http://msdn2.microsoft.com/en-us/library/system.web.httpcontext.user.aspx
Here is the logical to check if the identity is available.

VB.NET
' Gets the name if authenticated.
If User.Identity.IsAuthenticated Then
    Label1.Text = User.Identity.Name
Else
    Label1.Text = "No user identity available."
End If

C#
' Gets the name if authenticated.
if (User.Identity.IsAuthenticated)
    Label1.Text = User.Identity.Name;
else
    Label1.Text = "No user identity available.";


Environment.UserName is the running thread identity. If you have enabled Impersonation as Mark said, you can find out the returning result will be different. However this requires ASP.NET Impersionation. If you don't need ASP.NET Impersonation and dealing with the thread identity, you can ignore Environment.UserName if and just use User.Identity.Name.

Alternate ways to get username are are
  1. this
.Context.Request.LogonUserIdentity.Name
  • Request.LogonUserIdentity.Name
  • ref: http://forums.asp.net/t/1179997.aspx/1/10


    No comments:

    Post a Comment

    Devops links

      Build Versioning in Azure DevOps Pipelines