3

Unable to get the following standard code to work. Looking for a complete sample project or help on how to bug. The following code...

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.HttpContext.Session != null)
    {
        if (filterContext.HttpContext.Session.IsNewSession)
        {
            string cookie = filterContext.HttpContext.Request.Headers["Cookie"];
            if ((cookie != null) && (cookie.IndexOf("_sessionId") >= 0))
            {
                filterContext.Result = newRedirectResult("~/SessionExpired/Index");  //redirect anywhere to message user UI , never hits this breakpoint
                return;
            }
        }
    }
    base.OnActionExecuting(filterContext);

}

is standard for checking session expiration. However in my case the the line (cookie != null) && (cookie.IndexOf("_sessionId") >= 0) always returns false and thus the user is never redirected.

I am testing with a brand new wizard created MVC 4 project. I cannot find a complete download sample. I suspect my config my be wrong.

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="1" slidingExpiration="true" name=".ASPXFORMSAUTH" />  
</authentication>    
<sessionState mode="InProc" timeout="1" cookieless="false"/>

Please advise why this code fails or provide a link with a complete download sample project. .Net 4.5 | VS 2012 | local IIS Web Server , IIS Express

re: Detecting Session expiry on ASP.NET MVC

Community
  • 1
  • 1
user3042461
  • 31
  • 1
  • 3

2 Answers2

1

Try capitalizing the "s" in "_sessionId"

like:

sessionCookie.IndexOf("_SessionId") >= 0)

The search is case-sensitive. Also, the linked article you are referring to uses:

sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)
TSmith
  • 543
  • 5
  • 16
1

It's a really late answer, but it might help someone else.

If I'm not mistaken, for that approach to work, the forms authentication timeout must be set to a higher time than the session itself. That way when you're creating a new session (in the server memory), the cookie from the authentication will still be there in the user's computer to indicate that the user was recently logued.

You should try the following:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="1000" slidingExpiration="true" name=".ASPXFORMSAUTH" />  
</authentication>    
<sessionState mode="InProc" timeout="10" cookieless="false"/>
FercoCQ
  • 139
  • 3
  • 14