Monday, October 13, 2008

Response.Redirect() & ASP.Net Pipeline

I've just finished debugging a fun a bug related my nHibernate code. Essentially I was getting an error that indicated that I was trying to associate a collection with more then one active nHibernate session.

This made no sense within my architechure. I am using a static session manager which essentially creates and caches nHibernate sessions on demand. It stores the session within HttpContext or within CallContext depending upon the environment its loaded in. I then implemented a very simple HttpModule which would flush and close the session after the request is done processing. I was relying upon the PostRequestHandlerExecute event to do this cleanup.

What I discovered is that in one of my pages which had a Response.Redirect() in it, this event is never actually being called. The solution is simple. Use the EndRequest event instead.

One concern I have within the context of my nHibernate architecure is the idea of doing work on the database after the page has finished executing for the user. What happens if an error occurs? I might have shown the user that everything was ok but in fact it wasn't. I'd be curious if anyone has any advice about this one?

Enjoy
-Josh

2 comments:

seth said...

Hey, thanks for the post. I encountered a similar problem, and it looks like I will have to use the EndRequest event also. Unfortunately, I would like to be able to access session state which is not available in EndRequest. Just wondering if you or anyone else knows of a way to access session state from within an http module after response.redirect has been called?

Josh Berke said...

Quite welcome, off the top of my head I don't think its possible, at least not cleanly. By that point session state has already been written out.

You could store whatever you needed from Session in HttpContext.Items, this is a per request cloud of stuff, so it should still be available in EndRequest