To get the current logged in user at the system I use this code:
string opl = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.
Use this:
HttpContext.Current.User.Identity.Name
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:
Go to IIS → Sites → Your Site → Authentication
Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.
Now System.Web.HttpContext.Current.User.Identity.Name
should return something like this:
domain\username
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
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;
}
}
I ran in the same issue.
This is what worked for me:
Setting up Properties of Windows Authentication in IIS
NTLM has to be the topmost. Further Web.config modifications, make sure you already have or add if these do not exist:
<system.web>
<authentication mode="Windows" />
<identity impersonate="true"/>
</system.web>
<!-- you need the following lines of code to bypass errors, concerning type of Application Pool (integrated pipeline or classic) -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
See below a legit explanation for the two nodes and
Difference between <system.web> and <system.webServer>?
And, of course , you get the username by
//I am using the following to get the index of the separator "\\" and remove the Domain name from the string
int indexOfSlashChar = HttpContext.Current.User.Identity.Name.IndexOf("\\");
loggedInWindowsUserName = HttpContext.Current.User.Identity.Name.Substring(indexOfSlashChar + 1);