Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Session.IsNewSession issue with Google Chrome

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.

like image 969
PancakeParfait Avatar asked Mar 25 '11 16:03

PancakeParfait


2 Answers

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;
}
like image 187
Jakub Konecki Avatar answered Nov 01 '22 20:11

Jakub Konecki


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'

like image 44
dush88c Avatar answered Nov 01 '22 20:11

dush88c