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 existsif (filterContext.HttpContext.Session != null){//if new sessionif (filterContext.HttpContext.Session.IsNewSession){string cookie =filterContext.HttpContext.Request.Headers["Cookie"];//if cookie exists and sessionid index is greater than zeroif ((cookie !=null) &&(cookie.IndexOf("ASP.NET_SessionId") >= 0)){//redirect to desired session//expiration action and controllerfilterContext.Result =RedirectToAction("SessionExpired", "Home");return;}}}//otherwise continue with actionbase.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
One Comment
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.