Wednesday, September 08, 2010

Implementing Session Timeout Check in MVC

This took me awhile to get right; hope it saves some time for somebody else. I simply want to decorate a given controller (at the class level) with an attribute that will cause a redirect to login page (with a session timeout message) on session timeout while using forms authentication.

Here's the attribute:


     public class CheckSessionAttribute : ActionFilterAttribute 

     {

         public override void OnActionExecuting( ActionExecutingContext filterContext )

         {

             if ( filterContext.HttpContext.Session.IsNewSession )

             {

                 FormsAuthentication.SignOut();

                 filterContext.Controller.TempData[Constants .TEMPDATA_KEYS .TIMEOUT] = "Your session has timed out.  Please login again to continue." ;

                 filterContext.Result = new RedirectResult ( "/" );

             }

         }

     }

 

 


Now you need only check the presence of that TempData key on your logon view in order to show a proper timeout message instead of the standard login message.
Note the use of RedirectResult. The old Response.Redirect will do a proper redirect, but won't terminate the original request (even with the overload containing the parameter that tells it to do so). Response.Redirect should really raise an error when used in an MVC app.

2 comments:

Anonymous said...

you do know, the background colour of your page is black don't you, oh and your method names are also black. Nice Work!

Anonymous said...

thank you very much, it worked