Search code examples
asp.netsessionwebformsashx

How do I set a session variable in an ASHX file


I'm trying to set a session variable in an ASHX file. I read up on it a bit, and got this far:

  1. I set the variable in the ASPX file that calls the ASHX handler.
  2. I tried to reset the variable in the handler.

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.

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.

I've used this as guidance (How to access Session in .ashx file?), but obviously am missing something.

Can anyone advise me? I will continue to research and if I solve this, will post the solution.

See my code below.

In my .aspx file - I declare my session variable:

HttpContext.Current.Session["saml_session_id"] = string.Empty;

Then in the same file I post to the ashx file:

var response = Post("http://" + Request.ServerVariables["HTTP_HOST"].ToString() + "/API/Login.ashx", new NameValueCollection() {
            {"Username",Username},
            {"Password",Password}
        });

Then in my ashx file I have the following (this is a stripped down version):

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.

The when the request in the handler is finished processing, the next code in the ASPX file is this:

  if (Response.Status.ToString() == "200 OK") {
            Context.Response.Redirect("../Play.aspx?SessionId=" + HttpContext.Current.Session["saml_session_id"].ToString());
        }

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?


Solution

  • Make sure the handler implements System.Web.SessionState.IRequiresSessionState, just like in the link you provided.

    You shouldn't need to have the HttpContext.Current part, if you import the namespace.

    public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
          string Name = "";
          if (context.Session["filename"] != null)
             Name = context.Session["filename"].ToString();
        }
    }