如果会话已过期,则处理AJAX请求 [英] Handling AJAX requests if a session has expired

查看:135
本文介绍了如果会话已过期,则处理AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序(ASP.NET MVC 3 RAZOR)中,当会话到期并且用户尝试访问某些内容时,它将它们重定向到登录页面以重新登录.

In my app (ASP.NET MVC 3 RAZOR), when a session expires and the user tries to access something, it redirects them to the login page to re-login.

这很好,但是当从ajax请求进行调用时(例如,如果用户离开屏幕一段时间没有活动),它将在ajax请求中加载登录表单...这不是我想要的发生.

This is fine, but when calling from ajax requests (e.g. if the user has left their screen for a while with no activity), it will load the login form in the ajax request... Which is not what I want to happen.

处理此问题的最佳方法是什么?理想情况下,如果会话已过期,我想显示一个模式,以便用户无法访问其他区域.因此,即使他们离开了屏幕,一些jQuery也会检查会话,然后应用"Session Expired"(会话已过期)的模式

What is the best way of dealing with this? Ideally I'd like to show a modal if the session has expired so the user can't access other areas. So even if they leave the screen some jQuery will have checked the session and then applied a modal saying 'Session Expired'

我该怎么做?

例如

if(SESSION HAS EXPIRED) { showModal(); }

推荐答案

在这里我可以看到两个单独的可解决问题,因此我将分别讨论它们.

I can see two separate addressable issues here, so I will discuss them each separately.

作为AJAX结果返回的登录:
不仅返回登录屏幕,还返回一条指示会话已过期的消息.如果您的AJAX收到这样的消息,则表明用户需要重新登录.此时,您可以执行类似的操作

Login returned as AJAX result:
Rather than just return the login screen, return a message indicating that the session has expired. If your AJAX receives such a message, it knows the user needs to log back in. At this point, you can do something like

window.location = loginpageurlhere;

或者,您可以检查AJAX响应以查看它是预期响应还是登录页面.如果是登录页面,请使用上面的建议.

Alternately, you can check your AJAX response to see if it is an expected response or if it is the login page. If it is the login page, use the above suggestion.

如果用户闲置时间过长,则显示对话框:
为此,您需要知道用户处于非活动状态的时间.您可以通过几种不同的方法来执行此操作,其中一种方法如下:

Display dialog if user is inactive for too long:
For this, you need to know how long the user is inactive. You can do this in a couple different ways, one of which is as follows:

  • 页面加载时,初始化变量以用作倒计时.
  • 设置一个计时器,该计时器将在每次用完时间后递减计数器,然后重新启动.
  • 如果计数器达到零,则显示对话框并让用户重新登录.
  • 每次发生有效活动时(AJAX发布或您可能拥有的其他任何东西),请重置计数器.

您可以使用这两种方法中的任何一种,尽管如果您担心在无人值守的机器上保护数据,则第二种方法最好,因为您可以阻止屏幕并仅显示对话框,并且在用户不在了,而第一种方法在用户实际尝试对您的页面执行操作之前无法执行任何操作.

You could use either, of these methods, although if you are concerned about protecting data at an unattended machine, the second method would be best, since you can block the screen and only display the dialog, and it will happen while the user is away, whereas the first method can't do anything until a user actually attempts to perform an action on your page.

这篇关于如果会话已过期,则处理AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆