Accessing session state in an ASP.NET HttpModule

An ASP.NET project I’m working on requires a password protected area of the application. When I found out about the “Forms” authentication built into ASP.NET I thought I was all set on the authentication part of my project. I soon discovered though, that the server was losing session variables, which were created on login, while the user was still logged in. I decided to remedy this by logging the user out whenever the session variables were lost. The session variables would then be re-established when the user logged back in.

ASP.NET provides the HttpModule interface that allows one to create a class that will be executed on every request to the server. I went ahead and created my HttpModule and added the appropriate entries to my Web.config file. To my dismay, I received the dreaded “object reference not set to an instance of an object” exception message every time I tried to access the session inside my module. After a bit of hair pulling, I finally figured out where I went wrong.

If you want to access session state in your HttpModule be sure to add your EventHandler to the HttpApplication’s “PreRequestHandlerExecute” event, NOT the “BeginRequest” event.

This entry was posted in General. Bookmark the permalink.

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/5/d154205736/htdocs/wordpress/wp-includes/class-wp-comment-query.php on line 405

Comments are closed.