2

我在使用 mvc3 razor 构建的网站中有许多 ajax 调用。问题是会话超时后,如果使用 ajax 调用操作,那么它不会重定向到登录页面。我正在使用如下所示的属性处理会话超时。

public override void OnActionExecuting( ActionExecutingContext filterContext ) 
    {
        HttpContext ctx = HttpContext.Current;

       //  check if session is supported
        if(ctx.Request.IsAuthenticated)
        {


            if (ctx.Session != null)
            {

                // check if a new session id was generated
                if (ctx.Session.IsNewSession)
                {

                    // If it says it is a new session, but an existing cookie exists, then it must
                    // have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if (null != sessionCookie)
                    {
                        FormsAuthentication.SignOut();
                        const string loginUrl = @"~/Login/Login";
                        var rr = new RedirectResult(loginUrl);
                       filterContext.Result = rr;
                    }
                }
            }

        }
        else
        {

            ctx.Response.Redirect(@"~/Login/Login");
        }

        base.OnActionExecuting ( filterContext );
    }
4

1 回答 1

1

您传递的结果将向 ajax 请求发送一个 html 页面和一个 302 作为响应。还有其他方法可以处理此问题:

  1. 给一个自定义的响应码并在ajax请求中检查并在成功函数中检查响应码。
  2. 或者 Else 发送一个包含响应对象的 json 对象并在那里检查它

这可以在这两种方法的 ajaxComplete 事件中完成,并且可以添加到母版页/布局或任何有 ajax 调用的地方。

没有粘贴代码,因为它存在于许多其他问题上。 欢迎来到 StackOverflow Vaibhav!

于 2012-08-01T08:49:52.973 回答