如何获取当前登录的用户名

时间:2011-07-07 06:44:17

标签: c# .net

我正在构建一个小型Intranet应用,我需要在其中显示打开网页的人的用户名。

我试着用:

WindowsIdentity.GetCurrent().Name.ToString();

但这总是在网页上显示我的用户名。

4 个答案:

答案 0 :(得分:5)

请参阅THIS - 基本上您需要启用Integrated windows authentication并使用以下其中一项:

System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;    
string strName = p.Identity.Name;

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

string strName = Request.ServerVariables["AUTH_USER"]; //Finding with name    
string strName = Request.ServerVariables[5]; //Finding with index

所有3个案例都应该返回一个包含DomainName\WinNTLoggedUserName的字符串。

答案 1 :(得分:0)

您可以使用:

Page.User.Identity.Name

P.S:不要忘记检查实体是否先为空。

答案 2 :(得分:0)

使用此代码

if (User.Identity.IsAuthenticated)
 Label1.Text = User.Identity.Name;
else
 Label1.Text = "No user identity available.";

查看以下文章Forms Authentication in ASP.NET

答案 3 :(得分:0)

http://forums.asp.net/t/1102996.aspx/1。我认为您看到自己名字的原因是网络应用程序在您的凭据下运行。

因此请改用HttpContext.Current.User.Identity.Name并确保您已在web.config中启用Forms authentication