1

我无法处理 MVC 3 中的会话过期检查,最初我尝试使用 MVC 过滤器(操作执行)来检查会话,但我无法访问操作过滤器中的 request.session 变量,

我尝试在 global.asax 中使用 session_Start 方法,但问题是当会话过期时,它不会转到 session_start 方法

4

1 回答 1

0

您可以像这样创建属性

public class SessionExpireFilterAttribute:ActionFilterAttribute 
{
    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;


                    }
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") <= 0))
                    {
                        FormsAuthentication.SignOut();
                        const string loginUrl = @"~/Login/Login";
                        var rr = new RedirectResult(loginUrl);
                        filterContext.Result = rr;
                    }
                }
            }

        }
        else
        {

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

        base.OnActionExecuting ( filterContext );
    }
}
于 2012-08-13T11:24:58.243 回答