Monday, October 12, 2009

Accessing Session values for a HTTP Handler (ASHX)

When converting from a ASPX to ASHX for returning image data I ran into an issue with the HttpContext session being null. Turns out I just needed to add the IReadOnlySessionState interface to my IHttpHandler implementation.

An HTTP handler that needs to access session-state values must implement the IRequiresSessionState interface. Like INamingContainer, it's a marker interface and requires no method implementation. Note that the IRequiresSessionState interface indicates that the HTTP handler requires read and write access to the session state. If read-only access is needed, use the IReadOnlySessionState interface instead.
MSDN: Writing HTTP Handlers

Scott Hanselman: Getting Session State in HttpHandlers (ASHX files)