Is there a way using ASP.NET to always run some se

2019-07-14 01:24发布

问题:

I was wondering if there is any way to always run some server side code when a user leaves a page in ASP.NET. The page Unload event is no good because that doesn't get called if someone clicks on a link. Ideally I'd also like the code to run even if the user closes the browser.

I suspect what I'm asking isn't possible, but it doesn't hurt to ask

回答1:

Problem is, HTTP is a stateless protocol, so when the page has finished being served, you wont know if the user is still on the page or not.

The only way to acheive this would be a hidden piece of Javascript that constantly pings the server with it's session ID, or another similar mechanism. When the ping becomes unresponsive you can reasonably assume the page is not being viewed by the user anymore.

Here is a diagram that explains traditional HTTP message flow.



回答2:

im not really sure if you can do that but i have a workaround in mind. There is an event in the DOM called onbeforeunload. it get calls everytime a user leaves a page. you can try sending an ajax request to the server from this function.



回答3:

The closest thing you can come without creating too messy a solution is to enable ASP sessions. This will create a session on the server for each visitor, who will be identified by a cookie.

After a certain amount of inactivity from the visitor, the session will be closed, and a SessionEnd event will be raised. This you can hook up to in the Global.asax file.

I will not recommend this however, because HTTP is pr. definition a session-less protocol, and using server based sessions violates this fact, and are often problematic. Many solutions that use server based sessions run into problems when the user uses the browser-back button, and resubmits a form. Because the content of the submitted form no longer corresponds the data that exists in the server session.

Also, enabling server based sessions seriously hurts the scalability of the application.



回答4:

Not that I know of. You'll need to use javascript for that, and call a web service on the server side.