In this article I will explain with an example, how to use and access Session variables in Generic Handler in ASP.Net using C# and VB.Net.
By default, Session is disabled inside the Generic Handler and hence in order to use and access Session variables we need to inherit the IRequiresSessionState interface.
 
 
Adding Generic Handler
You will need to add a new Generic Handler (ASHX) file using Add New Item Dialog of Visual Studio as shown below.
Use and access Session variables in Generic Handler in ASP.Net
 
 
Building the Generic Handler for accessing Session
Inside the Generic Handler, the IRequiresSessionState interface which belongs to the System.Web.SessionState namespace is inherited.
Inside the ProcessRequest event handler of the Generic Handler, the value of Session variable is fetched and sent to client using Response.Write method.
C#
<%@ WebHandler Language="C#" Class="Handler" %>
 
using System;
using System.Web;
using System.Web.SessionState;
 
public class Handler : IHttpHandlerIRequiresSessionState
{
    public void ProcessRequest (HttpContext context) {
        string name = context.Session["Name"].ToString();
        context.Response.ContentType = "text/plain";
        context.Response.Write(name);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
 
VB.Net
<%@ WebHandler Language="VB" Class="Handler" %>
 
Imports System
Imports System.Web
Imports System.Web.SessionState
 
Public Class Handler : Implements IHttpHandlerIRequiresSessionState
   
    Public Sub ProcessRequest(ByVal context As HttpContextImplements IHttpHandler.ProcessRequest
        Dim name As String = context.Session("Name").ToString()
        context.Response.ContentType = "text/plain"
        context.Response.Write(name)
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net TextBox and a Button control.  
The Button has been assigned with an OnClick event handler.
<asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="Button1" Text="Send to Handler" runat="server" OnClick="Submit" />
 
 
Setting TextBox value in Session and calling the Generic handler in ASP.Net
When Submit button is clicked, the following event handler is executed.
Inside this event handler, the value of the TextBox is saved in a Session variable and page is redirected to the Generic Handler.
C#
protected void Submit(object sender, EventArgs e)
{
    Session["Name"] = txtName.Text;
    Response.Redirect("~/Handler.ashx");
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Session("Name") = txtName.Text
    Response.Redirect("~/Handler.ashx")
End Sub
 
 
Screenshot
Use and access Session variables in Generic Handler in ASP.Net
 
 
Demo
 
 
Downloads