ASP.NET MVC Session.IsNewSession issue with Google Chrome
Asked Answered
F

2

8

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.

Fulcher answered 25/3, 2011 at 16:17 Comment(0)
O
14

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;
}
Outfit answered 25/3, 2011 at 16:35 Comment(2)
Fascinating. So the fact that IE doesn't request a new session is the actual unusual behavior here?Fulcher
This has nothing to do with the browser, it's the behavior of ASP.NET.Outfit
D
1

We can add session_start method in Golbal.asax file in MVC appliaction.

  protected void Session_Start(object sender, EventArgs e)
      {                    
       HttpContext.Current.Session.Add("UserId" , null);
      }

Then when application starting your session will be created. and then session will be not isNewSession 'True', otherwise it will be always 'True'

Derose answered 17/7, 2015 at 5:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.