49

i'm trying to store some values in the Session from a Handler page, before i do a redirect to a WebForms page, that will pick up the Session values and pre-fill the WebForm:

public class Handler : IHttpHandler
{
   public void ProcessRequest(HttpContext context)
   {
      ...
      context.Session["StackOverflow"] = "overflowing";
      context.Response.Redirect("~/AnotherPage.aspx");
      ...
   }
   ...
 }

Except context.Session object is null.

How do i access Session state from a handler?

Community
  • 1
  • 1
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219

3 Answers3

112

Implement the System.Web.SessionState.IRequiresSessionState interface

public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
{   
  public void ProcessRequest(HttpContext context)  
  {      
    context.Session["StackOverflow"] = "overflowing";      
    context.Response.Redirect("~/AnotherPage.aspx");      
  }

}
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
JoshBerke
  • 66,142
  • 25
  • 126
  • 164
  • Note: you don't have to actually implement anything, just add the interface to your class. The web-server then sees that you're asking for it, and fills it in. – Ian Boyd Jun 29 '09 at 17:35
  • 3
    Yes which is still implementing the interface but since it's a marker interface there isn't any code we have to write other then the deriviation of the interface. – JoshBerke Jun 29 '09 at 20:33
  • 1
    For some reason mine wouldn't work, even with `IRequiresSessionState` specified. I had to use `IReadOnlySessionState`. I haven't researched why yet, but it is working.. – kodybrown Apr 02 '13 at 23:21
10

Implement IRequiresSessionState

masoud
  • 55,379
  • 16
  • 141
  • 208
Tim Hoolihan
  • 12,316
  • 3
  • 41
  • 54
7

Does implementing iRequiresSessionState resolve this?

What about doing an IHttpModule instead and overriding BeginRequest?

    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(context_BeginRequest);
    }
  • Does anyone know which is better performance-wise? – Chris Sep 16 '09 at 23:08
  • 2
    i am facing same problem i used iRequiresSessionState in my handler code but still i can't access session values. session keys are still 0. can anyone tell me about this? – Aqeel Feb 25 '13 at 10:52