Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • ASP.NET MVC: How to Check Session Timeout and Redirect to Login Page

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 39.3k
    Comment on it

    The following post captures the implementation details to manage session timeout in ASP.NET MVC. If session has expired we will redirect the user to login page

    First you need to make modificaions in web.config as below:

    <system.web>
        <sessionstate mode="InProc" timeout="2" cookieless="false"></sessionstate>
        <authentication mode="Forms">
          <forms loginurl="~/Home/Login" timeout="1">
        </forms></authentication>
     </system.web>
    

    Next you need to make a custom attribute as shown below. Here is the code which overrides ActionFilterAttribute.

    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class CheckSessionTimeOutAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            var context = filterContext.HttpContext;
            if (context.Session != null)
            {
                if (context.Session.IsNewSession)
                {
                    string sessionCookie = context.Request.Headers["Cookie"];
    
                    if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET&#95;SessionId") >= 0))
                    {
                        FormsAuthentication.SignOut();
                        string redirectTo = "~/Home/Login";
                        if (!string.IsNullOrEmpty(context.Request.RawUrl))
                        {
                            redirectTo = string.Format("~/Home/Login?ReturnUrl={0}",HttpUtility.UrlEncode(context.Request.RawUrl));
                        }
                        filterContext.HttpContext.Response.Redirect(redirectTo , true);
                    }
                }
            }
    
            base.OnActionExecuting(filterContext);
        }
    }
    

    Then in the Action you need to put attribute as below:

    [CheckSessionTimeOut]
    [Authorize(Roles = "Admin")]
    public ViewResult Index()
    {
        //Code goes here
    }

    Or Just add attribute one time as below :

    [CheckSessionTimeOut]
    public class HomeController : Controller
    {
      public ActionResult Index()
      {
         return Index();
      }
    }

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: