【问题标题】:How to get current windows user in asp.net?如何在 asp.net 中获取当前的 windows 用户?
【发布时间】:2015-05-06 07:22:51
【问题描述】:

我尝试了很多代码,它在我的本地服务器上成功运行。但我试着把远程服务器放在他们得到另一个字符串,如 IIS APPPOOL、“服务器名”...。我在 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();

【问题讨论】:

  • IIS 上的身份验证设置是什么?
  • System.Security.Principal.WindowsIdentity.GetCurrent().Name 应该可以正常工作。请务必提及您在 IIS 中的身份验证设置。
  • HttpContext.Current.User 应该可以工作如果您具有正确的身份验证设置并且用户已登录。如果您启用了匿名身份验证,则不会进行用户身份验证并且应用程序池的而是使用帐户。如果您使用任何其他类型的身份验证,HttpContext.Current.User 将返回登录用户。如果您同时拥有匿名和其他选项,则匿名会覆盖其他选项
  • 我都试过了,它在我的本地服务器上工作,但在远程服务器上不工作。另外,我不知道在 IIS 管理器中该做什么。
  • 匿名身份验证也必须禁用,否则优先 - 网络浏览器总是首先尝试匿名连接

标签: c# asp.net iis windows-authentication


【解决方案1】:

假设您使用的是 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

【讨论】:

  • 非常感谢沙林,但我不明白为什么要设置匿名身份验证禁用。它仍然无法正常工作。我无法获取 Windows 用户的用户名
  • 您是否在服务器和网站上都禁用了匿名身份验证?我上面的图片只显示点击服务器,但你肯定需要点击网站并从那里禁用它。服务器是可选的,因为您可能希望您托管的其他网站以不同的方式工作。
  • 当匿名身份验证被禁用时,网站想要获取但我想输入密码进行身份验证。以及如何设置服务器和网站?
  • 是的。有一个 Mode="Windows" 的身份验证元素。如果它不起作用,最好的办法是构建一个小型测试应用程序并部署它以删除所有应用程序逻辑并确保它与设置相关。试试这个support.microsoft.com/en-us/kb/323176
  • 真正的问题是我如何在没有身份验证的情况下获取用户名?我无法理解,抱歉沙林
【解决方案2】:

HttpContext.Current.User 应该没问题,但是 Windows 身份验证已启用这还不够:还要确保匿名身份验证已禁用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    相关资源
    最近更新 更多