Home > ASP.NET > Get Value Of Session variables from Generic Handlers

Get Value Of Session variables from Generic Handlers

if we are trying to access the value of session variables from Generic Handlers(.ashx files) like we acces from codebehind (.cs file) as the code below


public class MyHandler: IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";

string sessionValue = Convert.ToString(HttpContext.Current.Session["LoginUser"]);
}
}

we got NullReferenceException or Object reference not set to an instance of an object.

Solution

To overcome this exception and to access session variables from the HttpHandler, we should inherit the interface IReadOnlySessionState or IRequiresSessionState
(For this include the name space System.Web.SessionState first).

IReadOnlySessionState provides read-only access to session variables. And

IRequiresSessionState provides read/write access to session variables.

The working code is like this

using System.Web.SessionState;
public class MyHandler: IHttpHandler,IRequiresSessionState {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";

string sessionValue = Convert.ToString(HttpContext.Current.Session["LoginUser"]);
}
}

Advertisements
Categories: ASP.NET
  1. santosh
    December 8, 2011 at 6:59 am

    it is working only in IE not in mozilla, chrome etc….

  2. jaydeep
    March 29, 2012 at 9:46 am

    this is not working

    • March 30, 2012 at 4:04 am

      Hi what error you are getting? Make sure you are using the required namespace

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: