HTTP Session Lifecycle Hooks

Topics: Writing modules
Apr 4, 2011 at 11:23 AM

Is there a preferred way to deal with HTTP session lifecycle events  (i.e. Session_Start and Session_End) within Orchard? I did some searching through the code base, but nothing seemed to stand out. 

Apr 4, 2011 at 11:55 AM

Well it's best to avoid Session if at all possible :)

You won't be able to hook into Session_Start or Session_End because that would require modification to Global.asax.cs.

So it depends what you're needing to do. Orchard has loads of extensibility points and you want to find the best one for any particular job.

Perhaps implementing an IUserEventHandler would be useful if you need a per-user session, you can handle the LoggedIn and LoggedOut events to create and then clean up session objects.

You can also just use Session from your controller(s); it's not recommended to do so in views - put anything you'll need into your model at the controller level. I'm wondering why would you specifically need access to start and end of session?

Apr 4, 2011 at 12:16 PM

Sadly, I agree... but particular requirements mandate that certain actions be triggered at the start/end of a session. (fictitious example: sending off an email when the user's session expires given conditions X Y Z.) I saw IUserEventHandler, but users may not (won't) be authenticated so I do not believe that will help me? There's always for fighting requirements... :)  Thanks.

Apr 4, 2011 at 2:04 PM

Yep. IUser will be null when there's nobody logged in, so that wouldn't work.

Sessions can expire all the time for a variety of reasons, so I'd be worried if your website has conditions that necessitate sending an email just because of a session ending.

Maybe you should move to DB persisted session state if it's a critical factor.

I realise you said that was a fictitious example but it's hard for me to imagine a scenario that would absolutely necessitate knowledge of session start and end, what with it being a very indeterminate thing largely unrelated to any user experience.

Depending on your deployment scenario you can always just modify Global.asax, but then if you wanted to distribute this as a Module you'd have to expect any end users to also make those modifications.

A final option would be to implement a system where a "phantom user" is created for all unauthorised sessions. Then you can use the LoggedIn / LoggedOut events as well as moving your session data to the user profile - which is where most things I see session getting used for actually belong ;)