ASP.NET: How to access Session from handler? [duplicate]
Asked Answered
P

3

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?

Paz answered 29/6, 2009 at 14:18 Comment(0)
C
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");      
  }

}
Crimple answered 29/6, 2009 at 14:22 Comment(3)
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.Paz
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.Crimple
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..Phrygian
C
10

Implement IRequiresSessionState

Cymophane answered 29/6, 2009 at 14:26 Comment(0)
K
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);
    }
Kalvn answered 29/6, 2009 at 14:27 Comment(2)
Does anyone know which is better performance-wise?Montelongo
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?Pily

© 2022 - 2024 — McMap. All rights reserved.