vivek
vivek

Reputation: 31

How to handle Session timeout in MVC 3

I am having issues with frequent Session Time Out.

I want to write a common filter that I could use on each controller, filter should redirect the user to login and after log in back to from where user sent the last request.

Upvotes: 3

Views: 8665

Answers (4)

SpicyMikey
SpicyMikey

Reputation: 51

There's more here than meets the eye. Here's a more complete OnActionExecuting that uses the same concept already discussed above but adds a bit more. See inline comments for more info. The "InitializeSession" being called is a custom function which creates the basic attributes needed in Session State for running the site. "AlertWarning" is a Helper routine for displaying alerts. Everything else is boilerplate code.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
  var bRequiresAuthorization =
    (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0) ||
    (filterContext.Controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0);

  if (filterContext.HttpContext.Session != null)
  {
    if (filterContext.HttpContext.Session.IsNewSession)
    {
      //New session.  Initialize Session State
      bool b = InitializeSession(null);

      if (bRequiresAuthorization )
      {
        //Action requested requires authorized access.   User needs to authenticate this
        //new session first, so redirect to login
        string cookie = filterContext.HttpContext.Request.Headers["Cookie"];
        if ( (cookie != null) && (cookie.IndexOf("_SessionId=") >= 0) )
        {
          //An expired session cookie still resides on this PC, so first alert user that session is expired
          AlertWarning("Session timed out due to inactivity.  Please log in again.");
        }
        filterContext.Result = RedirectToAction("LogOut", "Authentication");
      }
    }
  }

  base.OnActionExecuting(filterContext);

}

Upvotes: 1

Rady
Rady

Reputation: 918

as mentioned above .. try this

public class SessionExpireAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Session != null) {
            if (filterContext.HttpContext.Session.IsNewSession) {
                filterContext.Result = new RedirectResult("/");//redirect to home page
            }
        }
    }
}

and then apply this filter over the action or controller [SessionExpire]

Upvotes: 0

37Stars
37Stars

Reputation: 2489

Have you tried the existing Authorize filter?

Upvotes: 0

gram
gram

Reputation: 2782

You could try something like this:

public class SessionExpireAttribute : ActionFilterAttribute {
    public override void OnActionExecuted(ActionExecutedContext filterContext) {
        base.OnActionExecuted(filterContext);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.HttpContext.Session != null) {
            if (filterContext.HttpContext.Session.IsNewSession) {
                var sessionCookie = filterContext.HttpContext.Request.Headers["Cookie"];
                if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
                    // redirect to login
                }
            }
        }
    }
}

Upvotes: 5

Related Questions