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 uploading the Files

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="HandlerCS" %>
 
using System;
using System.Web;
using System.Web.SessionState;
 
public class HandlerCS : IHttpHandler, IRequiresSessionState
{
    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="HandlerVB" %>
 
Imports System
Imports System.Web
Imports System.Web.SessionState
 
Public Class HandlerVB : Implements IHttpHandler, IRequiresSessionState
    
    Public Sub ProcessRequest(ByVal context As HttpContext)Implements 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 HTML Markup consists of following controls:
TextBox – For capturing user input.
Button – For redirect user input.
The Button has been assigned with an OnClick event handler.
<asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="btnSend" 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("~/HandlerCS.ashx");
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Session("Name") = txtName.Text
    Response.Redirect("~/HandlerVB.ashx")
End Sub
 
 

Screenshot

Use and access Session variables in Generic Handler in ASP.Net
 
 

Demo

 
 

Downloads