CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Accessing Session Variable in HttpHandler in ASP.Net
Submitted By Satheesh Babu B
On 11/3/2008 5:58:48 AM
Tags: ASP.Net,CodeDigest,HttpHandler  

By default, when you access session variables in HttpHandler it will throw an exception (Object reference not set to an instance of an object.).

 

To overcome this exception and to access session variables the HttpHandler should inherit the interface IReadOnlySessionState or IRequiresSessionState packed in System.Web.SessionState namespace.

 

  • IReadOnlySessionState provides read-only access to session variables.
  • IRequiresSessionState provides read/write access to session variables.

 

These are just a maker interface that specifies the session usages in HttpHandler which has no methods. Just inherit the interface and you can access the Session variables.

 

Refer the following code snippets for the usage!

 

Reading Session Variables in HttpHandler

<%@ WebHandler Language="C#" Class="Handler" %>

 

using System;

using System.Web;

using System.Web.SessionState;

 

public class Handler : IHttpHandler,IReadOnlySessionState {

   

    public void ProcessRequest (HttpContext context) {

 

        context.Response.Write(context.Session["Name"].ToString());

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

 

Reading/writing Session Variable in HttpHandler

<%@ WebHandler Language="C#" Class="Handler" %>

 

using System;

using System.Web;

using System.Web.SessionState;

 

public class Handler : IHttpHandler,IRequiresSessionState {

   

    public void ProcessRequest (HttpContext context) {

 

        context.Response.Write(context.Session["Name"].ToString()+"<br>");

        context.Session["Name"] = "CodeDigest.Com";

        context.Response.Write(context.Session["Name"].ToString());

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

}
Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..