title: Session variables in action filter
body: <p>I have an action filter checks whether or not a session variable <code>ID</code> is set. For development purposes, I have manually set this variable prior to the check.</p>
  
  <pre><code>public class MyActionFilterAttribute : ActionFilterAttribute
      {
          public override void OnActionExecuted(ActionExecutedContext context)
          {
  
              context.HttpContext.Session.Add("ID", 123123);
  
              int ID = (int)context.HttpContext.Session.Contents["ID"];
              var rd = context.HttpContext.Request.RequestContext.RouteData;
  
              TED _db = new TED();
  
              //if not in DB
              if (_db.Users.Find(ID) == null &amp;&amp; rd.GetRequiredString("action") != "NoAccess")
              {
                  RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                  redirectTargetDictionary.Add("action", "NoAccess");
                  redirectTargetDictionary.Add("controller", "Home");
                  redirectTargetDictionary.Add("area", "");
  
                  context.Result = new RedirectToRouteResult(redirectTargetDictionary);
              }
  
              base.OnActionExecuted(context);
          }
      }
  </code></pre>
  
  <p>As far as I understand, this code is run prior to any page, this <code>Session["ID"]</code> is always set. The site works fine if I am consistently testing, but it seems to break if I leave it for a while then try to continue testing. Here is the error I get:</p>
  
  <pre><code>int UserID = (int)Session.Contents["ID"];
  System.NullReferenceException: Object reference not set to an instance of an object.
  </code></pre>
  
  <p>Initially I thought the session may simply be expiring, but prior to any page loading, <code>Session["ID"]</code> should be getting set. What is the issue here?</p>