0

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 Answers1

0

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();
  }
}
Ajay Gupta
  • 703
  • 5
  • 11
  • this will work once I press any button on the site ,which I need to redirect once session end without doing any action on site – kerolos saber Apr 06 '22 at 09:54