Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Session expiry on ASP.NET MVC

Tags:

I have built a shopping cart that uses Session State to keep the shopping cart data while the user is browsing the store.

I have an issue where if I leave the browser window open for a long time on step1 of the shopping cart, then press "go to step 2", my actions throw an error because the step2 action assumes the session hasn't expired and the ShopCart object is in the correct state.

I would like this scenario to be nicer for my users, but I think i need to somehow detect if the session has expired so that on next request I can throw them to Step1.

I found the following code that claims to to solve the problem, but it doesn't work for me.

The IsNewSession condition is true but the condition

if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {    // handle expired session } 

always returns false and it never handles the invalid session. I'm confused.

Is this possible in ASP.NET (and MVC)?

like image 311
CVertex Avatar asked Sep 29 '09 06:09

CVertex


People also ask

How check session expired in ASP.NET MVC?

In web applications, session holds the information of current logged-in users. So, if the session expires in 20 minutes, then it is redirected to login page. In that case, we need to check if session exists (not null) in every action/ every controller which requires authentication.

How check session expired in asp net?

In asp.net, It is very simple to detect session time out and redirect the user to login page or home page. All you have to do is, specify the redirection page in session_start event handler in Global. asax file as shown below. If the session has timed out, the user will be redirected to the login page.

How can we check session on every page in ASP.NET MVC?

Go in Visual Studio and create New Project, select Web, then ASP.NET Web Application. Check it out in Account folder to understand the process and ASP.Net methods. Show activity on this post.


2 Answers

Way 1

Put this code in the Init / Load event of Page 2...

        if (Context.Session != null)         {             if (Context.Session.IsNewSession)             {                 string sCookieHeader = Request.Headers["Cookie"];                 if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))                 {                      if (Request.IsAuthenticated)                     {                         FormsAuthentication.SignOut();                     }                     Response.Redirect("Error Page");                 }             }         } 

Way 2

Alternative you can check whether the Session object exists before proceeding to work with it in Page 2, like this:

if (Session["Key"] != null) {    Object O1 = (Object) Session["Key"];  } else {     Response.Redirect("ErrorPage.aspx"); } 
like image 74
The King Avatar answered Sep 22 '22 17:09

The King


The King 's answer does not work for me. I have added FormsAuthentication.SignOut() in OnActionExcuting(). The Response.Redirect will not work!

if (Request.IsAuthenticated) {     FormsAuthentication.SignOut(); } 

This is my complete method

public class SessionExpireFilterAttribute : ActionFilterAttribute     {          public override void OnActionExecuting(ActionExecutingContext filterContext)         {             HttpContext ctx = HttpContext.Current;              // check if session is supported             if (ctx.Session != null)             {                  // check if a new session id was generated                 if (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))                     {                         string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;                         string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);                         string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;                         if (ctx.Request.IsAuthenticated)                         {                             FormsAuthentication.SignOut();                         }                         RedirectResult rr = new RedirectResult(loginUrl);                         filterContext.Result = rr;                         //ctx.Response.Redirect("~/Home/Logon");                      }                 }             }              base.OnActionExecuting(filterContext);         }     } 
like image 27
Tom Avatar answered Sep 21 '22 17:09

Tom