Steve Eisner
Steve Eisner

Reputation: 2005

ASP.NET HttpModule - guaranteed execution of pre- and post- handler code?

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!

Upvotes: 4

Views: 3025

Answers (2)

jlew
jlew

Reputation: 10591

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.

Upvotes: 3

Timothy Khouri
Timothy Khouri

Reputation: 31845

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%.

Upvotes: -2

Related Questions