title: How do I set a session variable in an ASHX file
body: <p>I'm trying to set a session variable in an ASHX file.  I read up on it a bit, and got this far:</p>
  
  <ol>
  <li>I set the variable in the ASPX file that calls the ASHX handler.</li>
  <li>I tried to reset the variable in the handler.</li>
  </ol>
  
  <p>I get an error saying that 'System.Web.HttpContext.Current.Session' is null. Like I've said I've done some reading and it SEEMS as though this should work, but for some reason I just can't get it to work for me.</p>
  
  <p>I added using using System.Web.SessionState; at the top of my handler but that didn't seem to do anything useful.  The Session variable ( HttpContext.Current.Session["saml_session_id"])  gets set with that, but doesn't seem to persist.  When I get to the aspx file and call HttpContext.Current.Session["saml_session_id"] from my immediate window, only NULL is returned.</p>
  
  <p>I've used this as guidance (<a href="https://stackoverflow.com/questions/11447196/how-to-access-session-in-ashx-file">How to access Session in .ashx file?</a>), but obviously am missing something.</p>
  
  <p>Can anyone advise me?  I will continue to research and if I solve this, will post the solution.</p>
  
  <p>See my code below.</p>
  
  <p>In my .aspx file - I declare my session variable:</p>
  
  <pre><code>HttpContext.Current.Session["saml_session_id"] = string.Empty;
  </code></pre>
  
  <p>Then in the same file I post to the ashx file:</p>
  
  <pre><code>var response = Post("http://" + Request.ServerVariables["HTTP_HOST"].ToString() + "/API/Login.ashx", new NameValueCollection() {
              {"Username",Username},
              {"Password",Password}
          });
  </code></pre>
  
  <p>Then in my ashx file I have the following (this is a stripped down version):</p>
  
  <pre><code>using System.Web.SessionState;
  
  //Some validation happens and a string called session_id gets generated.
  
  context.Session["saml_session_id"] = session_id;
  
  //while I'm in the ashx file, context.Session["saml_session_id"] persists.
  </code></pre>
  
  <p>The when the request in the handler is finished processing, the next code in the ASPX file is this:</p>
  
  <pre><code>  if (Response.Status.ToString() == "200 OK") {
              Context.Response.Redirect("../Play.aspx?SessionId=" + HttpContext.Current.Session["saml_session_id"].ToString());
          }
  </code></pre>
  
  <p>But HttpContext.Current.Session["saml_session_id"].ToString() is now blank again.  Basically it looks like the handler and the web form aren't communicating or the session isn't being shared.  I've checked to make sure the namespace is the same.  Anything else I should check?</p>