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

Tassisto picture Tassisto · Mar 24, 2011 · Viewed 201.8k times · Source

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.

Answer

BenCr picture BenCr · Mar 24, 2011

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