Question

I want to get the user name of the current logged in user. I am using the below code but it returns the user whose credentials are used in IIS application pool identity. The mvc website is deployed on a server.

I have used

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

string userid = Environment.UserName;

string userid = System.DirectoryServices.AccountManagement.UserPrincipal.Current.GivenName.ToString();

string userid = System.Web.HttpContext.Current.User.Identity.Name.ToString()

But nothing seems to give me correct answer.

I need to get user name in the constructor of the HomeController.

Below is my web.config

<authentication mode="Windows" />
<authorization>
    <allow users="*" />
</authorization>
Was it helpful?

Solution

just instead of

string userid = System.Web.HttpContext.Current.User.Identity.Name.ToString()

use this,this will work fine

string userid = HttpContext.Current.User.Identity.Name.ToString() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top