GoodGuyJim
GoodGuyJim

Reputation: 251

Programmatically refreshing session timeout in ASP.NET MVC4 application

In a nutshell, we want our sessions to last a business day and timeout in the evening. Currently I've set up some simple logic in Session_Start to set the timeout to the number of minutes left until 6pm.

My issue is on refresh the timeout gets set back to that value, so if you login at 8am your session will keep refreshing to 10 hours.

Is there any way to override the default logic for refreshing sessions to only set it to X if there is less than X remaining? So like if it gets under 20 minutes remaining I set it back to 20 minutes, but otherwise leave it alone?

Thanks for reading!

Upvotes: 1

Views: 7530

Answers (2)

sree
sree

Reputation: 1

protected void Page_Load(object sender, EventArgs e)
{
  int timeout = 20;
  var hour = DataTime.Now.Hour;
  var minutes =DataTime.Now.Minutes;
  var time = (hour * 60) + minutes;
  if (time <= 2000)
  {
    timeout = 2000 - time;
  }
  if (time > 2000)
  {
    //3000 minutes = midnight
    timeout = (3000 - time) + 2000;
  }
  Session.Timeout = timeout;
}

Upvotes: 0

Zerkey
Zerkey

Reputation: 795

Your timeout is set in global.asax only on Session_Start, so if a user logs in at 8am, the timeout would be set to 10 hours. If they access your site again within that time frame, their session is extended another 10 hours, because the logic in Session_Start does not fire again.

Solution 1 can offer is based off this article. Basically you add every new Session by reference to a List. At 6pm you could iterate through this list and Session.Abandon() any open Sessions. This would let you keep all your timeout logic in one or two files.

You can also put a method in your Page_Load() that gets the current time and adjusts the Session.Timeout property. Here is an example:

protected void Page_Load(object sender, EventArgs e)
{
    int timeout = 20;

    var hr = DateTime.Now.Hour;
    var min = DateTime.Now.Minute;
    var time = (hr * 60) + min;

    //1080 minutes = 6pm

    if (time <= 1080)
    {
        timeout = 1080 - time;
    }

    if (time > 1080)
    {
        //1440 minutes = midnight
        timeout = (1440 - time) + 1080;
    }

    Session.Timeout = timeout;

}

The code above will expire all sessions at 6pm server time. Try to put this on a master page if you have one.

Upvotes: 2

Related Questions