简体   繁体   English

会话启动Global.asax C#ASP.NET

[英]Session Start Global.asax C# ASP.NET

I have the following code: 我有以下代码:

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;
    }

The code is to get the windows user name. 该代码是获取Windows用户名。 From the session_start , I want to create a session which called WinAccount . session_start ,我想创建一个名为WinAccount的会话。 But, when I tried to call the session from one of my page (default.aspx) which is has master page on it. 但是,当我尝试从页面之一(default.aspx)调用会话时,该页面上有master page

Let say, on page_load: 假设在page_load上:

string sWinAccount = Session["WinAccount"].ToString();
Label1.Text = sWinAccount.ToString();

The web.config looks like: web.config看起来像:

<authentication mode="Windows"/>
<identity impersonate="false"/>
<authorization>
  <deny users="?"/>
</authorization>

Also, the properties of the project has been enabling the windows authentication mode. 此外,项目的属性已启用Windows身份验证模式。

When I run, it blanks. 当我跑步时,它一片空白。 Please advise. 请指教。

Thank you. 谢谢。

  1. Verify if the application is using Windows Authentication (check web.config). 验证应用程序是否正在使用Windows身份验证(检查web.config)。 If you are providing custom or forms authentication, you will need to set user details on success handler, not the session start; 如果要提供自定义或表单身份验证,则需要在成功处理程序上设置用户详细信息,而不是在会话开始时进行设置; and use CustomPrincipal rather than WindowsPrincipal . 并使用CustomPrincipal而不是WindowsPrincipal。
  2. If windows authentication is enabled, the user credential will be available on the very first request (session start) and can be retrieved are you mentioned in your code. 如果启用了Windows身份验证,则用户凭据将在第一个请求(会话开始)时可用,并且只要代码中提到您就可以检索该用户凭据。 Place a debugger in session start and verify if you are retrieving it properly or not. 将调试器放在会话启动中,并验证是否正确检索它。

尝试

string sUserAccount =System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring();

Session_Start event fired when a new client start their very first request to the app, not when the user is logged in. So in your case, the HttpContext.Current.User.Identity.Name is empty at the time Session_Start is called. 当新客户端向应用程序发起其第一个请求时(而不是在用户登录时)触发Session_Start事件。因此,在您的情况下,在调用Session_Start时HttpContext.Current.User.Identity.Name为空。 It worked as expected. 它按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM