在web应用程序中获取当前窗口用户

问题描述:

我正在使用string appNetworkUserId = WindowsIdentity.GetCurrent().Name;来获取我的web应用程序的当前用户。当我在本地运行机器时它工作。我得到domain\my name,但是当我在我的开发服务器上运行应用程序时,我得到NT AUTHORITY\NETWORK SERVICE而不是正在访问该网站的用户。在web应用程序中获取当前窗口用户

如何获取访问者的用户名到我的webapp?

我使用.NET 4.0和C#

这里是我最终使用。这工作。

System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent(); 
string[] a = Context.User.Identity.Name.Split('\\'); 
string appNetworkUserId = Context.User.Identity.Name.ToString(); 

你得到NT AUTHORITY\NETWORK SERVICE,因为这是运行IIS的身份。您在开发环境中获得自己的名称,因为那里的Web服务器以您登录的用户而不是系统用户身份运行。

如果你使用像一个在ASP.Net MVC的认证框架,你可以在一个控制器动作检查

User.Identity.Name 

首先,您需要设置您的网站以使用NTLM或集成Windows身份验证。否则,远程用户将不会被认证为Windows用户,并且您无法确定其用户帐户。

请参阅此处了解身份验证模式的讨论。

http://msdn.microsoft.com/en-us/library/ee825205(v=cs.10).aspx

http://technet.microsoft.com/en-us/library/cc733010(v=ws.10).aspx

一旦被配置,你可以获取当前用户:

using System.Security.Principal; 

// Obtain the authenticated user's Identity 
WindowsPrincipal winPrincipal = (WindowsPrincipal)HttpContext.Current.User; 
+0

要获得用户名,它会是这样的:winPrincipal.Identity.Name – NebulaSleuth 2014-10-17 17:46:36