Welcome to AspAdvice Sign in | Join | Help

Accessing Session from an HttpHandler

I've run into this before but forgotten about it.  I wrote an HttpHandler recently and was trying to access the Session object from the passed in HttpContext context object with

context.Session["foo"] = "bar";

and I encountered a NullReferenceException.  Some searching quickly yielded the answer, which is that in order to access Session from an HttpHandler you need to add a marker interface (meaning an interface with no implementation requirements) to your HttpHandler class.  I had been looking for the solution in the web.config, wondering if perhaps I had disabled Session there, before I remembered this little gotcha.

There are in fact several options you can choose from, and it's best for performance reasons if you limit your selection to only what is needed.  The marker interfaces are found in the System.Web.SessionState namespace, and include the following:

IRequiresSessionState - Specifies the HTTP handler requires both read and write access to session state values.

IReadOnlySessionState - Specifies the HTTP handler requires only read access to session state values.

Published Sunday, July 29, 2007 11:57 AM by ssmith
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Interesting Finds: July 30, 2007

Monday, July 30, 2007 1:27 PM by Jason Haley

# re: Accessing Session from an HttpHandler

Thanks a lot! That's really what i am looking for!

BR,

Emanuel

Monday, September 24, 2007 5:30 AM by Emanuel Carvalho

# re: Accessing Session from an HttpHandler

Thanks a lot! That's really what i am looking for!

Friday, November 23, 2007 3:26 PM by Go Compare .com Car Insurance UK

# re: Accessing Session from an HttpHandler

Perfect, thanks mate.

Tuesday, March 04, 2008 5:30 AM by Kevin Robinson

# re: Accessing Session from an HttpHandler

I was growing desperate over this. Thanks!

Sunday, May 04, 2008 5:45 PM by Mario Di Vece

# re: Accessing Session from an HttpHandler

what a simple problem, but confused me a lot

Friday, May 16, 2008 4:43 AM by steven

# re: Accessing Session from an HttpHandler

I'm doing that in .NET 1. Defined the interface in https handler. Still session is undefined. Any ideas? Thanks, Leah
Monday, May 26, 2008 10:16 AM by Leah Schneider

# re: Accessing Session from an HttpHandler

yeah this sorted me out too. cheers man thanks alot!

Monday, July 21, 2008 7:54 AM by James Jackson

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below