0

当用户关闭浏览器时,我想从数据库中删除一条记录。我要删除的记录属于关闭浏览器或注销的用户。我在全局中编写此代码,但它不起作用。有谁能够帮我。注意:我想删除具有注销用户用户名的记录。非常感谢全球代码:

 void Session_End(object sender, EventArgs e) 
    {


        string connStr = ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(connStr);
        SqlCommand sqlcmd = new SqlCommand("delete ChatRoomList where UserName=@UserName", sqlconn);
        sqlcmd.Parameters.AddWithValue("@UserName", (string)Session["User"]);
        sqlconn.Open();
        sqlcmd.ExecuteNonQuery();
        sqlconn.Close();

    }
4

2 回答 2

1

There is no reliable way to achieve this. Session_End event would only fire for in-process session state storage and the trigger point would be session expiration which is different than the browser close or user log-out.
So in your case, you may observe the event when your session actually gets timed out (if you have a logout link then you can force session expiry using Session.Abandon)

There are some other ways such as making an AJAX call to server to tell that user has logged out (or closing the browser window) and they may provide you with better results but again not 100% reliable. The most reliable way that I can think of is to have your own timer - i.e. to ping the server (using AJAX call) periodically from browser side and when pings are not received within certain time-out value, assume the user session to be dead/ended.

于 2013-01-08T10:51:55.090 回答
0

它可以在 IE 上运行

   window.onbeforeunload = function (event) {
    if (((window.event.clientX || event.clientX) < 0) || ((window.event.clientY || event.clientY) < 0)) // close button
    {
        //call here you you jQuery function to delete either page method, web service or http 
    }
    if ((window.event.clientX < 0) || (window.event.clientY < 0)) // close button
    {
        //call here you you jQuery function to delete either page method, web service or http 

    }
    else if (window.event.altKey == true || window.event.ctrlKey == true) // ALT + F4
    {
       //call here you you jQuery function to delete either page method, web service or http handler
    }
    else // for all other unload events
    {

    }

}
});
于 2013-01-08T11:07:53.023 回答