0

I want to access a value which is in session, when the session times out in my ASP.Net MVC 5 application. So, below is what I did.

  <system.web>
    <sessionState timeout="3"></sessionState>
  </system.web>

I added a value in session variable

System.Web.HttpContext.Current.Session["Val"] = myVal;

Now I want to access it when the session ends. So in global.asax I wrote below code.

  public void Session_OnEnd()
        {
            if (System.Web.HttpContext.Current.Session["Val"] != null)  // EXCEPTION
            {
                int TenantSessionId = (int)System.Web.HttpContext.Current.Session["Val"];
            }

        }

But after time out (3 minutes) I get exception as NULL REFERENCE in Session_OnEnd() Method. Kindly guide me. Have I missed something here? I just want to access the session variable. Or is it not possible to capture the session value just before the session is about to time out?

Kindly note that I am setting session variable when user logs in. So the setting up of session variable code is not in "Session_start". Just wanted to put out this information. But I am sure that the value is properly set in the session when the session_end() is getting called as per my code flow.

Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • Session is abandoned by the time you hit [Session_OnEnd](https://msdn.microsoft.com/en-us/library/ms524689(v=vs.90).aspx). There are several javascript techniques to direct users to a warning page or do a keep alive heartbeat. – Steve Greene Jan 25 '17 at 21:04
  • http://stackoverflow.com/questions/2030113/asp-net-session-variables-on-session-end – Unbreakable Jan 25 '17 at 21:05
  • above link tells that I can. Please guide me. – Unbreakable Jan 25 '17 at 21:05
  • Question is what are you trying to accomplish? If you want to warn the user their session is about to timeout you can do that with a little javascript in your _layout. If you want to track logged users, etc. I would suggest SignalR. – Steve Greene Jan 25 '17 at 21:10
  • I have a table when I just want to add one entry of time when that user has been signed/timed out. and I need the session Id to query my table add the timing of session out. – Unbreakable Jan 25 '17 at 21:11
  • I have a function already written. I just need to pass the session id on time out. – Unbreakable Jan 25 '17 at 21:11
  • I am a newbie. I don't know what is SignalR. I will look into it.' – Unbreakable Jan 25 '17 at 21:12
  • 1
    Not every lost session is going to hit that event. http://stackoverflow.com/questions/464456/httpcontext-current-session-vs-global-asax-this-session/471385#471385 – Steve Greene Jan 25 '17 at 21:14

0 Answers0