Redirect at Session Timeout in Global.asax in mvc4

2019-02-18 15:22发布

问题:

I am trying to detect when a session ends and then redirect user to the home page once this is done in my global asax file.

I am using below code which I found here

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();
                }
            }
        }
    }

I thought it was ok as it works in dev environment but when I try it on my server (IIS7) I get the error below.

'HttpContext.SetSessionStateBehavior' can only be invoked before 'HttpApplication.AcquireRequestState'

I've identified the issue using links like here but I just cant get it working. I believe issue is in the lines below

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

However I cant seem to get this to work on the server. Any ideas or suggestions?

回答1:

You can make a custom Action Filter for your controller that handles this:

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 );
        }
    }
}

And then, I would apply this filter to my Controller action methods like so:

 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();
            }
        }
    }