我有以下代码:
protected void Session_Start(object sender, EventArgs e)
{
WindowsPrincipal p = Thread.CurrentPrincipal as WindowsPrincipal;
string sUserAccount = HttpContext.Current.User.Identity.Name.ToString();
HttpContext.Current.Session["WinAccount"] = sUserAccount;
}
代码是获取窗口用户名。从session_start
,我想创建一个名为WinAccount
的会话。但是,当我尝试从我的一个页面(默认.aspx(调用会话时,该页面master page
。
让我们说,在page_load
string sWinAccount = Session["WinAccount"].ToString();
Label1.Text = sWinAccount.ToString();
web.config
如下所示:
<authentication mode="Windows"/>
<identity impersonate="false"/>
<authorization>
<deny users="?"/>
</authorization>
此外,该项目的属性一直启用 Windows 身份验证模式。
当我运行时,它空白。 请指教。
谢谢。
- 验证应用程序是否正在使用 Windows 身份验证(检查 web.config(。如果要提供自定义或窗体身份验证,则需要在成功处理程序上设置用户详细信息,而不是会话启动;并使用 CustomPrincipal 而不是 WindowsPrincipal 。
- 如果启用了 Windows 身份验证,则用户凭据将在第一个请求(会话启动(上可用,并且可以在代码中提及时检索。将调试器置于会话启动状态,并验证是否正确检索它。
试试
string sUserAccount =System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring();
Session_Start新客户端启动对应用程序的第一个请求时触发的事件,而不是在用户登录时触发。因此,在您的情况下,调用Session_Start时HttpContext.Current.User.Identity.Name
为空。它按预期工作。