簡體   English   中英

會話啟動Global.asax C#ASP.NET

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

我有以下代碼:

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

該代碼是獲取Windows用戶名。 session_start ,我想創建一個名為WinAccount的會話。 但是,當我嘗試從頁面之一(default.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身份驗證模式。

當我跑步時,它一片空白。 請指教。

謝謝。

  1. 驗證應用程序是否正在使用Windows身份驗證(檢查web.config)。 如果要提供自定義或表單身份驗證,則需要在成功處理程序上設置用戶詳細信息,而不是在會話開始時進行設置; 並使用CustomPrincipal而不是WindowsPrincipal。
  2. 如果啟用了Windows身份驗證,則用戶憑據將在第一個請求(會話開始)時可用,並且只要代碼中提到您就可以檢索該用戶憑據。 將調試器放在會話啟動中,並驗證是否正確檢索它。

嘗試

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

當新客戶端向應用程序發起其第一個請求時(而不是在用戶登錄時)觸發Session_Start事件。因此,在您的情況下,在調用Session_Start時HttpContext.Current.User.Identity.Name為空。 它按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM