Nov 23 2008
Detecting Session Timeouts using a ASP.Net MVC Action Filter
Some time ago, I read an article on how to detect a session timeout in a ASP.Net Web forms application by placing some code in a Base Page. The code worked for me and you could read more about it here. In my last post I mentioned that Microsoft released a beta version of their MVC implementation of ASP.Net and since them, I have been playing around with it. But, as with Web forms, I still needed a way to detect a session timeout and perform an action when a timeout is detected. So, I decided to use the same code implemented in the original article and implement it into my MVC project. I decided to write a custom action filter and apply it to my controller actions where I need to ensure that my session was still active. Here is the code for my action filter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
namespace Web {
public class SessionExpireFilterAttribute : ActionFilterAttribute {
public override void OnActionExecuting( ActionExecutingContext filterContext ) {
HttpContext ctx = HttpContext.Current;
// check if session is supported
if ( ctx.Session != null ) {
// check if a new session id was generated
if ( ctx.Session.IsNewSession ) {
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers[ "Cookie" ];
if ( ( null != sessionCookie ) && ( sessionCookie.IndexOf ( "ASP.NET_SessionId" ) >= 0 ) ) {
ctx.Response.Redirect ( "~/Home/Login" );
}
}
}
base.OnActionExecuting ( filterContext );
}
}
}
And then, I would apply this filter to my Controller action methods like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace Web.Controllers {
public class HomeController : Controller {
[SessionExpireFilter]
public ActionResult Index( ) {
// This method will not execute if our session has expired
// render Home Page
return View();
}
public ActionResult Login() {
// render Login page
return View();
}
}
}
The code is pretty straightforward. I just apply the [SessionExpireFilter] attribute on each method where I want to ensure that our session is still valid. If you have any questions, leave a comment under this post. Until next time…
Happy Coding!
