Implement Session Timeout In 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.

We have to two methods to check.
  1. We can check in every ActionResult.
  2. We can check in every controller.
The first option is not good because it gets repeated every time. So, avoid it and use the second option. 
 
We will create one custom Action Filter that handles session expiration and if session is null, it redirects to Login Action.
  1. namespace WebApplication.Filters {  
  2.     public class SessionTimeoutAttribute: ActionFilterAttribute {  
  3.         public override void OnActionExecuting(ActionExecutingContext filterContext) {  
  4.             HttpContext ctx = HttpContext.Current;  
  5.             if (HttpContext.Current.Session["userId"] == null) {  
  6.                 filterContext.Result = new RedirectResult("~/User/Login");  
  7.                 return;  
  8.             }  
  9.             base.OnActionExecuting(filterContext);  
  10.         }  
  11.     }  
  12. }  
Now, our Action Filter is created and we are ready to use it.

Apply to Controller

  1. [SessionTimeout]  
  2. public class MyController: Controller {  
  3.     [HttpGet]  
  4.     public ActionResult Index() {  
  5.             return View();  
  6.         }  
  7.         [HttpGet]  
  8.     public ActionResult Home() {  
  9.         return View();  
  10.     }  
  11. }  
Now, all the action methods are authenticated in this Controller. So whenever a session expires, the user is redirected on the login page.