How to access Session from an IHttpHandler
I’ve gotten a lot of use during my time coding with ASP.NET out of inheriting from IHttpHandler. I usually do this to handle dynamically-generated files in various formats (PDF, XLSX, and images to name a few). One thing that always irked me was the inability to access the HttpContext’s SessionState object to get things like connection strings and information about the logged-in user more easily to aid in generating my files; often I would end up encrypting those and cramming them into the query-string, which can present challenges such as replay attacks that I’d then have to find a way to prevent.
There is an answer, though. C# allows for a flavor of multiple-inheritance by allowing inheritance of multiple interfaces. In this case, inheriting both from IHttpHandler and IRequiresSessionState will let ASP.NET know that a) we want to handle requests and b) we need some session-state lovin’, yo. Sample below.