title: .NET Web API + Session Timeout
body: <p>I am creating a web service with web api controller. I want to be able to create a session and check the status of the session. I have the following:</p>
  
  <p>Controller:</p>
  
  <pre><code>public string Get(string user, string pass)
  {
          bool loginValue = false;
          loginValue = UserNamepassword(user, pass);
  
          if (loginValue == true)
          {
              HttpContext.Current.Session.Add("Username", user);                
              //session["Username"] = user; 
              //session.Add("Username", user);
              if ((string)HttpContext.Current.Session["Username"] != null)
              {
                  HttpContext.Current.Session.Add("Time", DateTime.Now);
  
                  return "Username: " + (string)HttpContext.Current.Session["Time"] + (string)HttpContext.Current.Session["Username"];
              }
              return "Logged in but session is not availabe for " + (string)HttpContext.Current.Session["Username"];
          }            
          else
              return "Login failed for " + user;
  }
  </code></pre>
  
  <p>WebConfig</p>
  
  <pre><code>public static void RegisterRoutes(RouteCollection routes)
      {
          var route = routes.MapHttpRoute(
              name: "SessionApi",
              routeTemplate: "api/{controller}/{user}/{pass}",
              defaults: new { user = RouteParameter.Optional, pass = RouteParameter.Optional }
          );
          route.RouteHandler = new MyHttpControllerRouteHandler();
      }
      public class MyHttpControllerHandler: HttpControllerHandler, IRequiresSessionState
      {
          public MyHttpControllerHandler(RouteData routeData): base(routeData){ }
      }
      public class MyHttpControllerRouteHandler: HttpControllerRouteHandler
      {
          protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
          {
              return new MyHttpControllerHandler(requestContext.RouteData);
          }
      }
  </code></pre>
  
  <p>Global.asax.cs</p>
  
  <pre><code>WebApiConfig.RegisterRoutes(RouteTable.Routes);
  </code></pre>
  
  <p>When I run this code I keep on getting null reference in the session.</p>
  
  <pre><code>HttpContext.Current.Session.Add("Username", user);                
  //session["Username"] = user; 
  //session.Add("Username", user);
  </code></pre>
  
  <p>Does anyone knows why I cannot set the session variable to anything. It does not matter which method I use non of the three are working. The code was taking from another post.</p>