ASP.NET MVC Session.IsNewSession issue with Google Chrome

PancakeParfait picture PancakeParfait · Mar 25, 2011 · Viewed 7.8k times · Source

I'm currently working on a Session expired piece of logic for my ASP.NET 3.5 MVC 2 project to log out a user and redirect them to the AccountController LogOn action.

I have the following attribute on all my actions that care about session state, and this piece of code works in IE 8, but not Firefox 4 or Google Chrome 10. The symptom is when I attempt to navigate to a view represented by an action with my [SessionExpireFilter] attribute, the ctx.Session.IsNewSession property in the below code is evaluating as "true" every time, even if I'm only seconds into my 30-minute session.

public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        // check if session is supported 
        if (ctx.Session != null && 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))
            {
                FormsAuthentication.SignOut();
                ctx.Response.Redirect("~/Account/LogOn");
            }
        }

        base.OnActionExecuting(filterContext);
    }
} 

Is there any way to figure out why Chrome and Firefox are behaving this way, but IE is not? Thanks in advance.

EDIT: This is not working in FF as I originally believed. I am being directed to my LogOn action immediately after logging in and attempting to access an action with my SessionExpireFilter attribute.

Answer

Jakub Konecki picture Jakub Konecki · Mar 25, 2011

ASP.NET will create a new session for every request unless you store something in it. Try adding the code below to your Global.asax. It works in my MVC2 and MVC3 apps with the same SessionExpireFilterAttribute.

protected void Session_Start()
{
    Session["Dummy"] = 1;
}