ASP.NET

Handlers and Session State

In Tutorial 13, we looked at session state. Session state works automatically within the context of System.Web.UI.Page. However, handlers need to turn on the ability to use session state deliberately.

The .NET architecture uses an interesting idiom known as marker interfaces. Marker interfaces are empty interfaces (without any methods or properties defined). Their sole purpose is to signal the runtime as to various aspects of the application. For example, ASP.NET runtime often uses them to turn on and off various features. When the runtime detects a marker interface as part of an object's class hierarchy, the runtime can bring into play certain features.

For a handler to use session state, it must have the System.Web.SessionState.IRequiresSessionState interface in its inheritance list. That way the runtime will know to load and store session state at the beginning and end of each request.

Listing 18-5 shows a handler with session state enabled.

Listing 18-5

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.SessionState;

using System.Web;

public class HandlerWithSessionState :
   IHttpHandler, IRequiresSessionState
{
   public void ProcessRequest(HttpContext ctx)
   {
      String strData = (String)ctx.Session["SomeSessionData"];

      if (strData == null)
      {
         ctx.Session["SomeSessionData"] = "This goes in session state";
      }
      ctx.Response.Write("This was in session state: " + strData);
   }

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