2017-06-27 34 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