在 MVC4 中的 Global.asax 中的会话超时时重定向

Shu*_*ark 3 c# asp.net-mvc session-timeout asp.net-mvc-3 asp.net-mvc-4

我试图检测会话何时结束,然后在我的全局 asax 文件中完成后将用户重定向到主页。

我正在使用我在这里找到的以下代码

global.asax:

protected void Session_Start()
    {
        if (Context.Session != null)
        {
            if (Context.Session.IsNewSession)
            {
                string sCookieHeader = Request.Headers["Cookie"];
                if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    //intercept current route
                    HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);
                    RouteData routeData = RouteTable.Routes.GetRouteData(currentContext);


                    //Substitute route Data Token Values for the Area
                    routeData.DataTokens["area"] = "";
                    routeData.DataTokens["UseNamespaceFallback"] = true;


                    //substitute route values
                    routeData.Values["controller"] = "home";
                    routeData.Values["action"] = "index";
                    routeData.Values.Add("timedOut", "true");
                    //routeData.Values["id"] = "timedOut";

                    IRouteHandler routeHandler = routeData.RouteHandler;
                    RequestContext requestContext = new RequestContext(currentContext, routeData);

                    IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
                    httpHandler.ProcessRequest(Context);

                    Response.Flush();
                    Response.End();
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我认为它可以在开发环境中工作,但是当我在我的服务器(IIS7)上尝试它时,我收到以下错误。

'HttpContext.SetSessionStateBehavior' 只能在 'HttpApplication.AcquireRequestState' 之前调用

我已经使用这里的链接确定了问题但我无法让它工作。我相信问题出在下面几行

IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
                    httpHandler.ProcessRequest(Context);
Run Code Online (Sandbox Code Playgroud)

但是我似乎无法让它在服务器上工作。有什么想法或建议吗?

Jas*_*ell 5

您可以为处理此问题的控制器制作自定义操作过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;


namespace Web {


    public class SessionExpireFilterAttribute : ActionFilterAttribute {


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


            // check if session is supported
            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 ) && ( sessionCookie.IndexOf ( "ASP.NET_SessionId" ) >= 0 ) ) {


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


            base.OnActionExecuting ( filterContext );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我会将这个过滤器应用到我的控制器操作方法中,如下所示:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;

    namespace Web.Controllers {

        public class HomeController : Controller {

            [SessionExpireFilter]
            public ActionResult Index( ) {
                // This method will not execute if our session has expired

                // render Home Page
                return View();
            }

            public ActionResult Login() {
                // render Login page
                return View();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)