2017-06-27 35 views
0

我想執行一個代碼,它將在數據庫中插入類似「Session expire」的內容來跟蹤用戶。但是,我的會話超時位於Web.configc# - 在超時前執行代碼

<system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    <sessionState timeout="20" mode="InProc" /> 
</system.web> 
<defaultDocument> 
     <files> 
     <add value="Login.aspx" /> 
     </files> 
</defaultDocument> 

然後我想要執行此代碼。

if (HttpContext.Current.Session["usersId"] == null && HttpContext.Current.Session["usersRole"] == null && HttpContext.Current.Session["usersDivision"] == null && HttpContext.Current.Session["notification"] == null) 
    { 
     string connstr = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString; 
     SqlConnection conn = new SqlConnection(connstr); 
     conn.Open(); 
     SqlCommand cmdlog = new SqlCommand("INSERT INTO Logs (logs_info,logs_date,users_id) VALUES (@info,@date,@id)", conn); 
     cmdlog.Parameters.AddWithValue("@info", "User " +sessionName+ " session timed out."); 
     cmdlog.Parameters.AddWithValue("@date", DateTime.Now); 
     cmdlog.Parameters.AddWithValue("@id", HttpContext.Current.Session["usersId"].ToString()); 
     cmdlog.ExecuteNonQuery(); 
     conn.Close(); 
     HttpContext.Current.Response.Redirect("../Login.aspx"); 
} 

如何在超時之前執行該代碼?

+0

**警告**您的代碼易受sql注入攻擊! –

+0

請參閱[本文](https://stackoverflow.com/questions/1413407/how-to-get-notified-of-session-end)瞭解一些見解。 – FrankerZ

+0

@ DanielA.White嘿喲先生白。我認爲有參數是好的,你可以分享爲什麼我的代碼是脆弱的? – Wowie

回答

0

您可以使用在Global.asax以下事件文件

void Session_End(Object sender, EventArgs E) { 
    // Do processing here 
} 

但是如果達到會話超時此事件纔會觸發。

要訪問會話變量,您可以使用this.Session而不是HttpContext.Current

希望它有幫助。

+0

嗨,我遵循你所說的,但有錯誤說'無法找到類型或命名空間名稱'SqlConnection'(你是否缺少使用指令或程序集引用?)' – Wowie

+0

這是由於命名空間不見了。試試[此解決方案](https://stackoverflow.com/a/29733842/1600909)。 – Wail