ASP.Net - How can we update row in database table if browser is closed
I have an asp.net web-forms application which is using entit开发者_Go百科y model. When a users logs in, we create a row in user_session table with timein. and when user logs out we update that row and put timeout.
Now problem is, when user closes the browser without logging out, how can we update the row in user_session table?
You can't. There is no way of the server being notified that a browser has been closed by the client. The best you could do is to schedule some job on your SQL Server which runs and updates rows. You may try also subscribing for the Session_End
event in Global.asax
but be careful because this event might never be triggered if you are using an out-of-process session.
Short answer is: You can't. That's why you shouldn't try to do such a silly thing.
The longer answer is: You have to put up with the delayed response of a session timeout. That could be a significant amount of time. In Global.asax there is an event called Session_End, which you can hook to do what you want.. but it won't show when the user closed their browser. It will only fire when the session has ended, which by default is 20 minutes after the last request. And that's only if it's an in-memory session and the process hasn't crashed.
The better solution is to just run a job every so often to clear the users online table. That solves the problem regardless, but requires more work for your job to figure out what to remove.
In your Global.asax.cs, you can code that in the Session_End
event. It will not happen till the session timeout (default 20 minutes), but it will happen. You will likely want to delete any existing records on Application_Start
and/or Application_End
events (the Application_End event does not execute when the computer or web process crashes so best to use Application_Start) to make sure you start off fresh when the web application loads.
You can use the Event Session_End in the Global.asax. There may be a delay between the browser closing and the actual session timeout on the server depending on your session settings.
I guess should be scheduled job that will close expired sessions like in AspState.
You can take a look into AspState database stored procedure DeleteExpiredSessions
to see what you need to do. This procedure job with name ASPState_Job_DeleteExpiredSessions
call each minute to close sessions.
Try the below code.
On the form_load
event in every page, write the below code.
Response.AppendHeader("Refresh", "60; URL=../default.aspx")
Default session time out is 20 minutes and I am using "60" seconds for this demo. If there is no activity in this period of time, then it goes back to the default or home page and we send a key to update the database "session key" or any other tag. This way we can possibly know the activity of the user or member.
This worked for me.
精彩评论