I'm trying to find an event that will fire immediately after all Application_Error
event handlers so that I can modify the response sent (messing with the status code and 'location' headers and creating a new body specifically) using a custom HttpModule.
I've tried hooking into Application_EndRequest
(as I've read that this is the only handler that is guaranteed to fire) but this is too late in the request processing to modify the response headers and I get a HttpException
:
Server cannot append header after HTTP headers have been sent.
Best Answer
I think ASP.Net launches a new response after ApplicationError, just for a different error-handling page. Try tacking into this response.
Update OK: Here's how to do it!
I wanted to make sure we can both attach an error handler and that we can gracefully handle the event in a page, so we can't make the last server error null, and we also want to be able to add headers!
In web.config, add:
Or whatever error specifically you're looking to catch. And under httpModules:
The code to log the error is in this module:
I just wrote it to the filesystem. You could use kernel file transactions or an exclusive lock or whatever, but because I know I will only write to this file from here, I chose a simple private semaphore.
I added this in Default.aspx.cs just to test:
Created file ErrorHandler.aspx with this in it (some parts omitted for shortness):
And here's the page-class:
Finally, I get these response headers at the ErrorHandler.aspx:
If you try to add to Response.Headers-collection directly you need to run IIS in pipeline mode: http://forums.asp.net/p/1253457/2323117.aspx
I hope this helps! Cheers Henrik