How to get current user who's accessing an ASP.NET application?

To get the current logged in user at the system I use this code:

string opl = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

I work on an ASP.NET application where I need this information. So I've put my application on a server and tried the code above, and I get "Network Service" in the string opl. I need to know the current user of the PC who accesses my ASP.NET application.


The quick answer is User = System.Web.HttpContext.Current.User

Ensure your web.config has the following authentication element.

<configuration>
    <system.web>
        <authentication mode="Windows" />
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</configuration>

Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application


Using System.Web.HttpContext.Current.User.Identity.Name should work. Please check the IIS Site settings on the server that is hosting your site by doing the following:

  1. Go to IIS → Sites → Your Site → Authentication

    IIS Settings

  2. Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.

    Authentication

  3. Now System.Web.HttpContext.Current.User.Identity.Name should return something like this:

    domain\username


If you're using membership you can do: Membership.GetUser()

Your code is returning the Windows account which is assigned with ASP.NET.

Additional Info Edit: You will want to include System.Web.Security

using System.Web.Security

The best practice is to check the Identity.IsAuthenticated Property first and then get the usr.UserName like this:

string userName = string.Empty;

if (System.Web.HttpContext.Current != null && 
    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
    System.Web.Security.MembershipUser usr = Membership.GetUser();
    if (usr != null)
    {  
        userName = usr.UserName;
    }
}