如何在ASP.NET中获取当前Windows用户?

3

我尝试了很多代码,在我的本地服务器上可以成功运行。但是当我将其放到远程服务器上时,会得到一些其他字符串,例如IIS APPPOOL,“servername”等。我在IIS管理器中更改了一些设置,但失败了。

如何在远程服务器上获取用户名?

我尝试了一些代码:

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

  string strName = p.Identity.Name;

或者

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

或者

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

或者

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

或者

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

或者

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

1
IIS的身份验证设置是什么? - danish
1
System.Security.Principal.WindowsIdentity.GetCurrent().Name 应该可以正常工作。请在 IIS 中提及您的身份验证设置。 - Rohit416
1
如果您拥有正确的身份验证设置并且用户已登录,则 HttpContext.Current.User 应该可以工作。如果启用了匿名身份验证,则不会进行用户身份验证,而是使用应用程序池的帐户。如果您使用任何其他类型的身份验证,则 HttpContext.Current.User 将返回已登录的用户。如果您同时具有匿名和其他选项,则匿名将覆盖其他选择。 - Panagiotis Kanavos
我尝试了两种方法,它们在我的本地服务器上可以运行,但在远程服务器上无法运行。此外,我不知道在IIS管理器中该怎么做。 - Çağrı Kutlu
在 IIS 管理器设置中启用了 Windows 身份验证。 - Çağrı Kutlu
1
匿名身份验证也必须被禁用,否则它会优先生效 - 网页浏览器总是首先尝试匿名连接。 - Panagiotis Kanavos
2个回答

4
假设您正在使用IIS 7.5,请按照以下步骤操作。其他版本将类似。然后,所有上述获取用户名的方法都将起作用。
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

Double click on Authentication

Right click on Anonymous authentication and disable it and likewise enable Windows authentication

Check which application pool your website is using Check the Application pool settings


非常感谢,Sarin。但是我不明白为什么我得到了“设置匿名身份验证禁用”的结果,而且它还是不起作用。我无法获取Windows用户的用户名。 - Çağrı Kutlu
你是否在服务器和网站上都禁用了匿名身份验证?我上面的图片只显示了点击服务器,但你肯定需要点击网站并从那里禁用它。服务器是可选的,因为你可能希望托管的其他网站工作方式不同。 - sarin
当禁用匿名身份验证时,网站想要获取信息,但我想输入密码进行身份验证。我该如何设置服务器和网站? - Çağrı Kutlu
是的。有一个Mode="Windows"的身份验证元素。如果它不起作用,最好的方法是构建一个小的测试应用程序并部署它以删除所有应用程序逻辑,并确保它与设置相关。请尝试此链接:https://support.microsoft.com/zh-cn/kb/323176 - sarin
真正的问题是,我如何在没有身份验证的情况下获取用户名?抱歉,我不理解。 - Çağrı Kutlu

3

HttpContext.Current.User应该没问题,但是需要确保匿名身份验证已禁用,因为启用了Windows身份验证不足以保证。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接