Is there a way using ASP.NET to always run some server side code when a user leaves a page?

流过昼夜 提交于 2019-12-24 03:10:55

问题


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.



来源:https://stackoverflow.com/questions/4679573/is-there-a-way-using-asp-net-to-always-run-some-server-side-code-when-a-user-lea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!