c# - 如何在 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);
解决方案
WindowsIdentity.GetCurrent()
获取网站运行的身份,通常是应用程序池身份。这不是登录到您网站的当前用户(除非您使用模拟)。
改为使用HttpContext.Current.User.Identity
,它将为您提供用于验证当前 HTTP 请求的身份。
这假定您的 Windows 身份验证工作正常。
推荐阅读
- google-apps-script - 使用 Google App Script 来自 google drive 的 OCR 图像
- aspnetboilerplate - 重置密码的正确方法是什么?
- javascript - 使用 Javascript 查找对象中的重复值
- python - 无法强制 virtualenv 使用 Python 3.5
- java - 如何减小 LineChart 上的线条宽度
- github - CircleCI/Github 拉取请求状态未显示
- css - 如何检测操作系统是否在浏览器中处于暗模式?
- android - RecyclerView 是否为空
- python - Python正在将字符转换为符号
- mysql - SQL - 每个 id 只显示一行