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.
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;
}
} }
|