65

I have an HttpHandler that is run on a client page (cross domain, not on our IIS server, etc) and when they click on our embedded link it fires off the Handler on our server. So far everything is working normally.

I am now trying to use the System.Web.HttpContext.Session object but it is null. I am thinking it is null because we don't have a session until our HttpHandler is invoked? And multiple calls to the handler will create a new session per call? If this is the case did MS just disable the Session object when calling into a HttpHandler? Can anyone confirm this?

If this is the case, what do you do to maintain state between calls? Some sort of SQL based data object? A file?

TIA

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Keith Barrows
  • 24,802
  • 26
  • 88
  • 134

4 Answers4

149

Have your HttpHandler implement the IRequiresSessionState interface. It will enable session state use. IRequiresSessionState can be found in the System.Web.SessionState namespace.

TAS
  • 2,039
  • 12
  • 17
Mara Morton
  • 4,429
  • 1
  • 21
  • 12
31

I think you have to implement the empty interface IReadOnlySessionState, so the context will be loaded.

edit to add:

According to Michael Morton's answer, you can also implement IRequiresSessionState, which will give you write access also to the Session object

Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103
  • 2
    For many httphandler uses IReadOnlySessionState is best, at least when one is only checking session state not saving it, but the main reason this is the better answer is because an HttpHandler implements IReadOnlySessionState or IRequiresSessionState rather than inherits (classes can inherit only from other classes). – JackArbiter Nov 01 '13 at 15:40
  • We found IReadOnlySessionState was substantially faster. – David Homer Jun 16 '21 at 14:28
11
using System; 
using System.Web;
using System.Web.SessionState;
public class DownloadHandler : IHttpHandler, IReadOnlySessionState
{
   public bool IsReusable { get { return true; } }

   public void ProcessRequest(HttpContext context)
   {
       context.Response.Write(context.Session["kmx"]);
   }
}
KMX
  • 2,631
  • 1
  • 23
  • 28
-10

try using the current context...

System.Web.HttpContext.Current.Session
Joe Davis
  • 1,019
  • 8
  • 14