Accessing Session from an HttpHandler

Date Published: 29 July 2007

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.

Steve Smith

About Ardalis

Software Engineer

Steve is an experienced software architect and trainer, focusing currently on ASP.NET Core and Domain-Driven Design.

Ardalis

Copyright © 2020