How to get current windows user in asp.net?

2019-04-11 19:27发布

问题:

I tried lots of code it Works successfuly in my local server. But I tried it to put remote server they get another strings such as IIS APPPOOL, "servername" .... I change to some settings in IIS manager but I failed. How can i get username in remote server

I tried some codes like:

System.Security.Principal.WindowsPrincipal= System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;

  string strName = p.Identity.Name;

or

string strName = HttpContext.Current.User.Identity.Name.ToString();

or

string Name = Environment.GetEnvironmentVariable("USERNAME");

or

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

or

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
    string usernamex = currentIdentity.Name.ToString();

or

HttpContext.Current.User.Identity.Name.ToString();

回答1:

Assuming you are using IIS 7.5 do the following. Other versions will be similar. All the above ways of getting the username should then work.

1) Double click on Authentication (This can be done at server level and your web site level so check both!)
2) Right click on Anonymous authentication and disable it and likewise enable Windows authentication
3) Click Basic settings. Check which application pool your website is using. Ensure it is using pass-through authentication for an "Application User" by clicking "Connect As" i.e. A user using a browser will be the person requesting authentication.
4) Click "Application Pools". Click the Application pool from (3). Click "Advanced Settings". Check the Identity is set to ApplicationPoolIdentity



回答2:

HttpContext.Current.User should be ok, but the fact that Windows authentication is enabled it's not enough: also ensure anonymous authentication is disabled.