简体   繁体   中英

How to redirect to action result from timer elapsed event in mvc

I have scenario where i need to redirect to new action result on timer elapsed event, here is my code, its not working currently.

   public ActionResult ExistingClientConfirmation(AppointmentRequest model, FormCollection collection)
        {
            var appointment = AppointmentRequest.GetCurrent();

          try
            {
                if (!ValidateAppointmentNotBooked(appointment))
                {
                    return indexAction(appointment);
                }
                ValidateSession(appointment);
                if (collection != null)
                {
                    model.TimeInterval = collection["hdnTimeInterval"];
                    System.Timers.Timer aTimer = new System.Timers.Timer();
                    aTimer.Elapsed += (sender, e) => OnTimedEvent(sender, e, appointment);
                    aTimer.Interval = 5000;
                    aTimer.Enabled = true;
                }
                if (model != null)
                {
                    appointment.TimeInterval = model.TimeInterval;
                    appointment.Client = model.Client;
                }
                return RedirectToAction("ExistingClientConfirmation");

            }
            catch (Exception ex)
            {
                return HandleAndRedirectException(ex);
            }
        }

 public void OnTimedEvent(object source, ElapsedEventArgs e,AppointmentRequest appointment)
        {
            HomePage(appointment);
        }

        public ActionResult HomePage(AppointmentRequest appointment)
        {
            return indexAction(appointment);
        }

during debug i saw its hitting the elapsed event for every five seconds, but not redirecting. Any help please?

Thanks in advance.

As said in my comment, you can't return an action result from a timer event. The client has already received the result from the controller and your timer event has nothing to return to. So your timer event would fire, the method Homepage() would be executed and the result would be thrown away.

The http context has a session object that you can use to store all kinds of objects, for instance the expiration date. You can access the current session from your controller methods. Store the date there, retrieve it in your controller actions and act depending on the situation. That would also work when the user reloads a page or opens a second tab. Closing and reopening the browser (or tab) will create a new session, effectively resetting your session timer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM