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.
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;
}
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With