如何在MVC jQuery的ajax调用,如果会话超时后重定向到新的页面? [英] how to redirect to new page after jquery ajax call in MVC if session timeout?

查看:309
本文介绍了如何在MVC jQuery的ajax调用,如果会话超时后重定向到新的页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1 - 我有打电话的动作,并且动作返回一个视图,该视图在一个特定的股利(认为这是与相应的视图更新DIV菜单)打开一个Ajax链接 2 - 如果会话超时返回我的登录视图

1- I have an Ajax link that call an action and that action returns a view , that view open in a specific Div (consider it as a menu that update the div with the corresponding view) 2- if session timeout the returned my logon view

所以,如果我点击的链接和会话超时,登录视图股利不是整个页面

so if i click on the link and session is timeout , the log on view open in the div not in the whole page

我应该这样做,如果会话超时它返回在新页面的登录视图在我的分区?

what i should do so if the session timeout it return logon view in new page in on my div?

推荐答案

这是有效的方式来处理会话到期是创建一个自定义授权属性,并返回一个 HTTP 403 响应,如果会话已过期并处理Ajax请求。

An efficient way to handle a session expiry is to create a custom Authorization attribute and return a HTTP 403 response if the session has expired and were dealing with an ajax request.

要创建一个Ajax知道授权属性,你可以从 AuthorizeAttribute 继承和要求,例如类型检查覆盖 HandleUnauthorizedRequest 事件。 IsAjaxRequest()

To create an Ajax aware authorization attribute you can inherit from AuthorizeAttribute and override the HandleUnauthorizedRequest event with a check on the type of request eg. IsAjaxRequest()

public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // Fire back an unauthorized response
            filterContext.HttpContext.Response.StatusCode = 403;
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

然后,只需装饰你的AjaxAuthorize控制器或动作的属性,就像你通常会与授权

Then just decorate your controllers or actions with the AjaxAuthorize attribute just as you normally would with Authorize

[AjaxAuthorize(Roles = "1,2,3,4,5")]
public class HomeController 
{

然后,如果你正在使用jQuery你可以处理通过创建一个全球性的Ajax错误处理程序中的403响应。

Then if you're using jQuery you can handle the 403 response by creating a global ajax error handler.

    $.ajaxSetup({
        error: function (x, e) {
            if (x.status == 403) {
                alert("Sorry, your session has expired. Please login again to continue");
                window.location = "/login";
            }
        }
    });

这篇关于如何在MVC jQuery的ajax调用,如果会话超时后重定向到新的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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