Handling AJAX requests if a session has expired
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.
This is fine, but when calling from ajax requests (eg 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.
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'
How would I do this?
eg
if(SESSION HAS EXPIRED) { showModal(); }
I can see two separate addressable issues here, so I will discuss them each separately.
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;
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:
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.
您可以查看以下博客文章,其中介绍了一种很好的技术,允许您在此情况下让服务器返回401状态代码,这些代码可以在客户端捕获并执行相应操作(向用户显示模式)。
You can set a global error handler in jQuery which will be called every time an error is caught by jQuery ajax. If a session times out then a 401 error is thrown. This can be caught and the user redirected to the login page.
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if (jqxhr.status == 401) {
window.location.replace("/login");
}
});
The global error handler should always be added to the document object.
链接地址: http://www.djcxy.com/p/71790.html下一篇: 处理AJAX请求,如果会话已过期