How to use Session values in an HttpHandler

When writing a custom HttpHandler, by default you have no access to the Session object. Doing something like HttpContext.Current.Session also returns null. The workaround is quite simple:

Reference the System.Web.SessionState namespace:

using System.Web.SessionState;

 ...and decorate the handler with either the IRequiresSessionState attribute:

public class MyHandler:IHttpHandler, IRequiresSessionState 

or the IReadOnlySessionState attribute:

public class MyHandler:IHttpHandler, IReadOnlySessionState

with the latter giving read only access to the seesion object.

 

Hope that helps.

 

EDIT: As pointed out...IReadOnlySessionState and IRequiresSessionState are not attributes, but empty interfaces. This is pretty apparent from the fact that we're not decorating the handler, rather the handler implements the interface [and since it's an empty interface, we don't need to implement anything to do so]. Late night blogging can lure the fingers to strange routes on the keyboard, it seems 8)

13 Comments

Comments have been disabled for this content.