首页 > 解决方案 > 如何在 ASP.net 中显示与域名分开的用户名,如域\用户名:以便它可以用作值

问题描述

我正在设置一个应用程序,在页脚中,一个 Site.Master 文件包含一个文本标签以显示“欢迎,用户名”。尽管我应用了正确的代码,但我似乎无法获取用户名的文本。

我对此很陌生,所以看不到我在做什么了。非常感谢你。

在 Site.Master 文件中:

<asp:Label ID="Label1" runat="server" ></asp:Label>

在 Site.Master.cs 文件中:

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
if (windowsIdentity == null)
throw new InvalidOperationException("WindowsIdentity is null");
string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last();

Label1.Text = String.Format("Welcome,{0}", nameWithoutDomain);


[解决方案]

 var windowsIdentity = HttpContext.Current.User.Identity;

            if (windowsIdentity == null)
                throw new InvalidOperationException("WindowsIdentity is null");
            string nameWithoutDomain = HttpContext.Current.User.Identity.Name.Split('\\').Last();

            Label1.Text = String.Format("Welcome,{0}", nameWithoutDomain);    

标签: c#windows-authenticationdomain-namelogin-name

解决方案


WindowsIdentity.GetCurrent()获取网站运行的身份,通常是应用程序池身份。这不是登录到您网站的当前用户(除非您使用模拟)。

改为使用HttpContext.Current.User.Identity,它将为您提供用于验证当前 HTTP 请求的身份。

这假定您的 Windows 身份验证工作正常。


推荐阅读