How to detect that session time out automatically and redirect to login Action in asp.net MVC?

1.5k Views Asked by At

How to detect that session time out automatically and redirect to login Action in asp.net MVC once session end ?

I tried to redirect to login action from Session_End() method but it not working

 protected void Session_End(Object sender, EventArgs e)
        {
            
            object USerID = this.Session["sessionUserID"];
            if (USerID!=null)
            {
                int result = BLL.Base.UserBLL.LogOut(int.Parse(USerID.ToString()),true);
                Session.Clear();
                
            }
           
        }
1

There are 1 best solutions below

1
On

You can do this with the Action filter

public class SessionExpireAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            // check  sessions here
            if( HttpContext.Current.Session["sessionUserID"] == null ) 
            {
               filterContext.Result = new RedirectResult("~/Home/Index");
               return;
            }
            base.OnActionExecuting(filterContext);
        }
    }

Now you can use at specific action or at controller level

[SessionExpire]
public ActionResult Index()
{
     return Index();
}

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