views:

747

answers:

2

Basically, I'm trying to write the following (pseudocode) in an ASP.NET HttpModule:

*pre-code*
try { handler.ProcessRequest(...) }
catch (Exception) { *error-code* }
finally { *post-code* }

I've found that I can hook into HttpModule.PreExecuteHandler for "pre-code" and .Error for "error-code". But PostExecuteHandler doesn't seem to be running reliably.

BeginRequest and EndRequest run reliably but are too early for the code I need to write, which requires inspection of the handler that was chosen to execute. The handler isn't chosen until after BeginRequest.

Is there a best practice for writing this kind of wrapper?

Thanks!

A: 

Add this to your Global.asax file:

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
 //
}

protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
 //
}

That should work 100%.

Timothy Khouri
Thanks, I appreciate the answer - but I'm looking to do this without a Global.ASAX file, in an HttpModule. Also, I believe (but haven't yet tested in an ASAX) that if someone does a Response.End inside the handler, the PostRequestHandlerExecute will never run. Only the End event will.. (?)
Steve Eisner
+1  A: 

There is no way to do what you want (in a HttpModule, at least), other than to not call Response.End. This article explains it pretty well and offers an alternative to Response.End in case it is a side-effect of your having called Server.Transfer.

jlew
Thanks - that's exactly what I was looking for, not for Server.Transfer but for Request.End(). PostRequestHandlerExecute definitely doesn't execute, but I think that EndRequest does get called even in this case? Oh well, I'll go test...
Steve Eisner