有没有办法使用 ASP.NET 在用户离开页面时始终运行某些服务器端代码?
我想知道当用户离开 ASP.NET 中的页面时是否有任何方法可以始终运行一些服务器端代码。页面卸载事件不好,因为如果有人单击链接,则不会调用该事件。理想情况下,即使用户关闭浏览器,我也希望代码能够运行。
我怀疑我所问的问题是不可能的,但问一下也没什么坏处
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是,HTTP 是一种无状态协议,因此当页面完成服务后,您将不知道用户是否仍在该页面上。
实现这一目标的唯一方法是使用一段隐藏的 Javascript,不断使用其会话 ID 或其他类似机制对服务器进行 ping 操作。当 ping 变得无响应时,您可以合理地假设用户不再查看该页面。
这是解释传统 HTTP 消息流的图表。
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.
我不太确定你是否可以做到这一点,但我想到了一个解决方法。
DOM 中有一个名为 onbeforeunload 的事件。每当用户离开页面时,它就会接到电话。您可以尝试通过此函数向服务器发送 ajax 请求。
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.
在不创建过于混乱的解决方案的情况下,您可以做的最接近的事情是启用 ASP 会话。这将在服务器上为每个访问者创建一个会话,并通过 cookie 来识别访问者。
访问者处于一定时间的不活动状态后,会话将关闭,并引发 SessionEnd 事件。您可以将其连接到 Global.asax 文件中。
不过我不会推荐这个,因为 HTTP 是公关的。定义无会话协议,并使用基于服务器的会话违反了这一事实,并且通常会出现问题。当用户使用浏览器后退按钮并重新提交表单时,许多使用基于服务器的会话的解决方案都会遇到问题。因为提交的表单内容不再对应于服务器会话中存在的数据。
此外,启用基于服务器的会话会严重损害应用程序的可扩展性。
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.
据我所知没有。为此,您需要使用 javascript,并调用服务器端的 Web 服务。
Not that I know of. You'll need to use javascript for that, and call a web service on the server side.