Search code examples
c#asp.nethttpmodule

Response Modification in HTTP Module


I built an http module in C# that just overrides the EndRequest of a lifecycle, checks the status code of the response header and modifies the response code it if needs be. Something like:

HttpContext context = ((HttpApplication)source).Context;
if (context.Response.StatusCode == 200)
{
    context.Response.StatusCode = 404;
}

This seems to work fine for me when I test it against localhost (real IIS), but when I enable intranet access and test from another computer it fails every time.

The error I am seeing when I test via another computer is:

"Server cannot set status after HTTP headers have been sent."

I also noticed that requests the same file twice, whereas locally it only requests the file once. I heard someone say something about output buffering, but I also tried setting the on BeginRequest response OutputBuffer to true and got the same results.

Thoughts?


Solution

  • You need to modify the response before the headers are sent. I've never had to do this, but I would guess the correct event would be PreSendRequestHeaders. link

    Here's an example of setting headers in this event.

    If this event doesn't work for you, check out some events after the handler's post process in the pipeline: http://blogs.msdn.com/b/carloc/archive/2007/12/19/application-page-and-control-lifecycle.aspx Be careful, though, because you may have to rewrite your code for the IIS 7 integrated pipeline.