Handle asp.net MVC session expiration

Here is a really simple way to handle a session expiration in asp.net MVC using a base controller.  Having all controller inherit from a basecontoller and overriding the OnActionExecuting event allows for checking the session before all actions are executed.

Here is the code

public class BaseController : Controller
{
    protected override void OnActionExecuting
        (ActionExecutingContext filterContext)
    {
        // If session exists
        if (filterContext.HttpContext.Session != null)
        {
            //if new session
            if (filterContext.HttpContext.Session.IsNewSession)
            {
                string cookie =
                    filterContext.HttpContext.Request.Headers["Cookie"];
                //if cookie exists and sessionid index is greater than zero
                if ((cookie !=null) &&
                    (cookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    //redirect to desired session 
                    //expiration action and controller
                    filterContext.Result =
                        RedirectToAction("SessionExpired", "Home");
                    return;
                }
            }
        }
        //otherwise continue with action
        base.OnActionExecuting(filterContext);
    }
}
}

This simple but effective method ensures that no actions will be executed if the session has expired forcing the user to login again

-Craig

This entry was posted in .NET Framework and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted September 14, 2011 at 10:24 pm | Permalink

    Appreciate your sharing this ” Handle asp.net MVC session expiration “. Your website is very well made. I am just stunned at the details you’ve got in this net site. It divulges precisely how effectively you understand this specific matter. Just bookmarked http://blog.tallan.com/2010/06/25/handle-asp-net-mvc-session-expiration, will return for more information. I came across exactly the details I want immediately after browsing in all places and merely couldn’t obtain. What a great web page.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*