title: Redirect at Session Timeout in Global.asax in mvc4
body: <p>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.</p>
  
  <p>I am using below code which I found <a href="http://forums.asp.net/t/1519552.aspx" rel="nofollow noreferrer">here</a></p>
  
  <p>global.asax:</p>
  
  <pre><code>protected void Session_Start()
      {
          if (Context.Session != null)
          {
              if (Context.Session.IsNewSession)
              {
                  string sCookieHeader = Request.Headers["Cookie"];
                  if ((null != sCookieHeader) &amp;&amp; (sCookieHeader.IndexOf("ASP.NET_SessionId") &gt;= 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();
                  }
              }
          }
      }
  </code></pre>
  
  <p>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. </p>
  
  <p>'HttpContext.SetSessionStateBehavior' can only be invoked before 'HttpApplication.AcquireRequestState' </p>
  
  <p>I've identified the issue using links like <a href="https://stackoverflow.com/questions/10639822/mvc3-application-inside-webforms-application-routing-is-throwing-a-httpcontext-s">here</a> but I just cant get it working.  I believe issue is in the lines below</p>
  
  <pre><code>IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
                      httpHandler.ProcessRequest(Context);
  </code></pre>
  
  <p>However I cant seem to get this to work on the server.  Any ideas or suggestions?</p>