[英]Session_End in Global.asax.cs not firing
我有一個Asp.net Web應用程序,其中使用FormsAuthentication進行用戶登錄。
我想防止同一時間多次登錄同一用戶。 為此,我將FormsAuthentication超時設置為15分鍾,將Session.timeout設置為15分鍾。
當用戶關閉瀏覽器而不注銷時,或者如果用戶不活動15分鍾,它將不會在global.asax.cs文件中觸發Session_End()事件。 我想更新Session_End()事件中的數據庫字段。
登錄代碼:
if (Membership.ValidateUser(username, password))
{
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(15),
false,
FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1"));
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
context.Response.Cookies.Add(authCookie);
context.Response.Redirect("/HomePage", false);
}
的Global.asax.cs:
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
Session.Timeout = 15;
}
protected void Session_End(Object sender, EventArgs e)
{
PersonObject person = new PersonObject();
// calling the function to update entry in database
person.ResetUserLoginStatus(HttpContext.Current.User.Identity.Name);
}
更新數據庫中條目的功能:
public bool ResetUserLoginStatus( string username="")
{
string sql = "UPDATE Person SET IsLogged=0 WHERE Person = @Person";
PersonObject person = new PersonObject();
object id = person.ExecuteScalar(sql, new Dictionary<string, object>() {
{ "Person", (!string.IsNullOrEmpty(username)?username:User.Name )}
}, "Person");
return true;
}
Web.config文件:
<authentication mode="Forms">
<forms loginUrl="/Security/Login.ashx/Home" name="SecurityCookie" timeout="15" slidingExpiration="true">
</forms>
</authentication>
<sessionState timeout="15" mode="InProc"></sessionState>
問題在於,當瀏覽器關閉時,不會調用ResetUserLoginStatus()方法,並且我無法將我的值重置為0。由於該字段尚未重置為0,因此該用戶將無法再次登錄。
請提出建議。
Session_End實際上不是那么有用或可靠。 一方面,它僅在接收到HTTP請求並已呈現響應時才在管道處理結束時觸發。 這意味着它對於僅關閉瀏覽器的用戶不起作用。 此外,除了某些類型的會話狀態外,該事件永遠不會觸發-例如,它不適用於State Server或基於SQL的會話狀態。 底線是您不能依靠它來維護明確的“已登錄”標志。
相反,我將存儲“收到的最后一頁請求”時間戳。 然后,您可以推斷出“已登錄”標志的值; 在過去15分鍾內提交請求的任何用戶仍將登錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.