title: How to capture session values when session time out in ASP.Net MVC 5 in global.asax file
body: <p>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.</p>
  
  <pre><code>  &lt;system.web&gt;
      &lt;sessionState timeout="3"&gt;&lt;/sessionState&gt;
    &lt;/system.web&gt;
  </code></pre>
  
  <p>I added a value in session variable</p>
  
  <pre><code>System.Web.HttpContext.Current.Session["Val"] = myVal;
  </code></pre>
  
  <p>Now I want to access it when the session ends. So in global.asax I wrote below code.</p>
  
  <pre><code>  public void Session_OnEnd()
          {
              if (System.Web.HttpContext.Current.Session["Val"] != null)  // EXCEPTION
              {
                  int TenantSessionId = (int)System.Web.HttpContext.Current.Session["Val"];
              }
  
          }
  </code></pre>
  
  <p>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?</p>
  
  <p>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.</p>