mustcodemore.com

10.01.2007

Session State in a Handler File

For a project we're working on we need to use HttpHandlers to do a lot of the heavy lifting when a user first comes to a site. The handlers help us determine what "type" of user it is and help us fork off processes and objects to different pages or applications based on a number of inputs (which the handler gets).

Working with this was going well until i needed to supply a constructor a sessionId. No problem i gave it a bit of the old :

context.Session.SessionId;

To my dismay i realized that the entire sessioin object was null. Because the handler file intercepts the request before the asp.net frameword processes it there is no session information available (see ISAPI Extensions). What to do? What to do?!?!

Of course i sent a post out to a forum and then minutes after posting it figured it out myself. The key is to make your HttpHandler implement the IRequiresSessionState interface. This interface allows the Handler to write or read from the Session state.

There are two options for this interface (and it needs no construct)

IRequiresSessionState - Read and Write access to session object
IReadOnlySessionState - Read only access to session object.

Implementation is quite simple. Take a simple Handler Code class and add the following using statement:

using System.Web.SessionState;

Then inherit the class from the Interface (as well as your handler interface)

 public class BaseHandler : IHttpHandler, IRequiresSessionState  
{
public virtual void ProcessRequest(HttpContext context)
{

}

public bool IsReusable
{
get
{
return false;
}
}
}


Pretty easy huh? And now its session enabled so i can pass my objects to my page.

Labels: , , ,

0 Comments:

Post a Comment

<< Home