Using Session with in HTTPHandler

In this tip I am going to discuss how you can use Session with in your custom HTTPHandler.  By default if you try to read or write anything related with Session, you will get an NullReferenceException. If you want to plug Session with in your HttpHandler you have to implement the  marker Interface (Interfaces with no methods are called marker interfaces ) either IRequiresSessionState or IReadOnlySessionState .

Implementation of IRequiresSessionState will provide both Read and Write operation to HTTPHandler on the other hand IReadOnlySessionState  will provide only the read only access.

Both these interfaces are the marker interface with no method define.

image
Once you have the implementation of the above interface, you can access the Session with in your HttpHandler.The role of the marker interface here is to let ASP.NET Runtime know that this  handler using Session and based on that it will load the session related information.

Below is the sample code snippet to read and write Session info with in Handler.

public class SessionEnabledHandler : IHttpHandler, IRequiresSessionState
{
///
/// Gets a value indicating whether another request can use the instance.
///

///
/// true if the instance is reusable; otherwise, false.
public bool IsReusable
{
get
{
return true;
}
}

///
/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the interface.
///

///An object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. public void ProcessRequest(HttpContext context)
{
string SessionData = string.Empty;

if (context.Session["SessionData"] == null)
{
context.Session["SessionData"] = "MySessionData";
}
else
{
SessionData = (string)context.Session["SessionData"];
}

context.Response.Write("Session Data From HttpHandler" + SessionData);
}
}

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.