ASP.NET MVC : Handle Session Expire Using Custom Attribute

Managing a session is a common task in web applications. In this article I will show you how to handle sessions with custom attributes.

Scope

In most web applications we previously would keep the user information in the session after login. In some pages we use this session. Before using this session we need to check whether the session is null or not. If the session is null then it should redirect to the login page then after successful login the system should automatically redirect to the requested page.

Here is the code inside SessionExpire Attribute:

  1. public class SessionExpire : ActionFilterAttribute  
  2. {  
  3.     public override void OnActionExecuting(ActionExecutingContext filterContext)  
  4.     {  
  5.   
  6.   
  7.         if (HttpContext.Current.Session["UserInfo"] == null)  
  8.         {  
  9.             FormsAuthentication.SignOut();  
  10.            filterContext.Result =  
  11.           new RedirectToRouteResult(new RouteValueDictionary   
  12.             {  
  13.              { "action""Index" },  
  14.             { "controller""Login" },  
  15.             { "returnUrl", filterContext.HttpContext.Request.RawUrl}  
  16.              });  
  17.   
  18.             return;  
  19.         }  
  20.     }  
  21.   
  22. }  
SessionExpire attribute inherits from ActionFilterAttibute and in the OnActionExecuting method we will handle our session. If Session["UserInfo"] is null then it will redirect to the login controller after sign-out.

Example

Here we have implemented SessionExpire in ManageAccountController.
  1. [SessionExpire]  
  2.  public class ManageAccountController : BaseController  
  3.  {  
  4.      public ActionResult Index()  
  5.      {  
  6.            
  7.          return View();  
  8.      }  
  9.  }  
It will redirect to our LoginController, if the session is null. Here we have returned the URL. We will keep this URL in ViewBag.ReturnUrl.
  1. public class LoginController : BaseController  
  2. {  
  3.      
  4.     public ActionResult Index(string returnUrl)  
  5.     {  
  6.         ViewBag.ReturnUrl = returnUrl;  
  7.         return View();  
  8.     }  
  9. }
Then we will post loginController with retrun URL. After model validation and form authentication it will redirect to the requested page, here is ManageAccountController.
  1. @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) // in Index.cshtml  
  2.   
  3. [HttpPost]  
  4. public ActionResult Index(Model objUser, string returnUrl)   
  5. {  
  6.     ViewBag.ReturnUrl = returnUrl;  
  7.       
  8.     if (ModelState.IsValid)  
  9.     {  
  10.        FormsAuthentication.SetAuthCookie("Username"false);  
  11.         return RedirectToLocal(returnUrl);  
  12.     }  
  13.     else  
  14.     {  
  15.         return View();  
  16.     }  
  17. }  
  18.   
  19. public ActionResult RedirectToLocal(string returnUrl)  
  20. {  
  21.     if (Url.IsLocalUrl(returnUrl))  
  22.     {  
  23.   
  24.         return Redirect(returnUrl);  
  25.     }  
  26.     else  
  27.     {  
  28.         return RedirectToAction("Index""Home");  
  29.     }  
  30. }  

Up Next
    Ebook Download
    View all
    Learn
    View all