0

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>
ssingh
  • 294
  • 1
  • 4
  • 19
  • try this...HttpContext.Current.User.Identity.Name – Kartikeya Khosla Aug 01 '14 at 12:46
  • I tried this but its returning empty string. – ssingh Aug 01 '14 at 12:50
  • My fault actually. HttpContext worked. I was trying to check while debugging so was getting empty string, but when I deployed and checked the user name it gave the correct result. Can you post your answer so that I can accept it as an answer. – ssingh Aug 03 '14 at 19:12

1 Answers1

1

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() 
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • System.Web.HttpContext.Current.User.Identity.Name.ToString() is working fine. Just that while debugging it would only show empty string but if we deploy the site then it works perfectly. – ssingh Aug 07 '14 at 14:55