Wednesday, 31 October 2012

How to implement Hard Session Expiry in ASP.NET?

Hard Session Expiry means, the session must expire e.g. after 4 hours.

You could write the below code in the global.ascx file:

private const string MyDeadlineSessionKey = "MyDeadline";

 private static readonly int SessionDeadlineInMinutes = initializeSessionDeadline();
 
 private static int initializeSessionDeadline()
 {
  string sessionDeadlineInString = SettingHelper.Instance.GetFromConfigManager("SessionDeadlineInMinutes");
  int sessionDeadlineInInt = 60; // 1 hour by default
  int.TryParse(sessionDeadlineInString, out sessionDeadlineInInt);
  return sessionDeadlineInInt;
 }

 void Application_PreRequestHandlerExecute(object sender, EventArgs e)
 {
  HttpSessionState session = HttpContext.Current.Session;

  // not all requests have session
  if (session != null && session[MyDeadlineSessionKey] != null)
  {
   var myDeadline = DateTime.Parse(session[MyDeadlineSessionKey].ToString());

   if (DateTime.Now.Subtract(myDeadline).TotalMinutes > 0)
   {
    session.Abandon();
   }
  }
 }

 void Session_Start(object sender, EventArgs e)
 {
  // the value will be read from config file
  Session.Add(MyDeadlineSessionKey, DateTime.Now.AddMinutes(SessionDeadlineInMinutes));
 }

No comments: