In this article I will explain 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.
 
For this article, I’ll be setting value of Session variable on a Page and then that variable will be accessed in the Generic Handler.
 
Setting Session value on ASP.Net Page
Following is the HTML Markup of the ASP.Net Page consisting of a TextBox and a Button.
<asp:TextBox ID="txtName" runat="server" Text="" />
<asp:Button ID="Button1" Text="Send to Handler" runat="server" OnClick="Submit" />
 
Inside the Button Click 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("~/Handler.ashx")
End Sub
 
 
Using and accessing Session variables inside the Generic Handler
In order to access Session inside the Generic Handler, we need to inherit the IRequiresSessionState interface which belongs to the System.Web.SessionState namespace.
Inside the ProcessRequest event handler of the Generic Handler, the value is fetched from the Session variable and is 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 : 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="Handler" %>
 
Imports System
Imports System.Web
Imports System.Web.SessionState
 
Public Class Handler : 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
 
 
Demo
 
 
Downloads