MVC : Manage Session Expire Using Attribute

facebooktwittergoogle_plusredditpinterestlinkedinmail

Managing a session is a common task in web applications. In this article I will show you how to handle session 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:

 
    public class SessionExpire : ActionFilterAttribute  
    {  
        public override void OnActionExecuting(ActionExecutingContext filterContext)  
        {  
            if (HttpContext.Current.Session["UserInfo"] == null)  
            {  
                FormsAuthentication.SignOut();  
               filterContext.Result =  
              new RedirectToRouteResult(new RouteValueDictionary   
                {  
                 { "action", "Index" },  
                { "controller", "Login" },  
                { "returnUrl", filterContext.HttpContext.Request.RawUrl}  
                 });  
 
                return;  
            }  
        }  
 
    }

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.

    [SessionExpire]  
     public class ManageAccountController : BaseController  
     {  
         public ActionResult Index()  
         {  
 
             return View();  
         }  
     }

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.

    public class LoginController : BaseController  
    {  
 
        public ActionResult Index(string returnUrl)  
        {  
            ViewBag.ReturnUrl = returnUrl;  
            return View();  
        }  
    }

Then we will post loginController with retrun URL. After model validation and form authentication it will redirect to the requested page, here is ManageAccountController.

   @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) // in Index.cshtml  
 
[HttpPost]  
public ActionResult Index(Model objUser, string returnUrl)   
{  
    ViewBag.ReturnUrl = returnUrl;  
 
    if (ModelState.IsValid)  
    {  
       FormsAuthentication.SetAuthCookie("Username", false);  
        return RedirectToLocal(returnUrl);  
    }  
    else  
    {  
        return View();  
    }  
}  
 
public ActionResult RedirectToLocal(string returnUrl)  
{  
    if (Url.IsLocalUrl(returnUrl))  
    {  
 
        return Redirect(returnUrl);  
    }  
    else  
    {  
        return RedirectToAction("Index", "Home");  
    }  
}

You might also like:

The following two tabs change content below.

Tom Mohan

Tom Mohan is a technologist who loves to code and build. He enjoys working on Microsoft Technologies. Tom specializes in ASP.NET MVC, Web API , Azure, C# ,WPF, SQL etc and holds a Bachelor engineering degree in Computer Science. Certification : MCSD , MCTS