Ben Lowery's HttpCompressionModule and Excluding Paths

We've had a lot of success using Ben Lowery's HttpCompression module in regards to cutting down our bandwidth on text intensive pages.  The only problem we've had with using the compression module has been with existing pages that were using Response.Flush (it would throw up the "Server cannot append header after HTTP headers have been sent" exception) .  Well, no problem, right?  Ben's excellent module supports the ability to exclude paths in web.config.  And this solution works great on our test machines.  The problem was that when we went live, everything broke in regards to excluding paths.  It would start throwing the "Server cannot append header after HTTP headers have been sent" all over again.

After sitting down and tracking down what we thought could be causing the exception, it really came down to our live site being in the root of the web, and during testing it would be in a subfolder of some sort.  Digging into the code we found the root of the evil:

string realPath = app.Request.Path.Remove(0, app.Request.ApplicationPath.Length+1);
if(settings.IsExcludedPath(realPath)){
   // skip if the file path excludes compression
   return;
}

Opps, Request.ApplicationPath is going to be "\" in the root folder, but it would be something like "SubFolder" on our test machines. Darren Neimke has a good write up on the subject.  Anyways, ripping out ApplicationPath.Length + 1 characters isn't going to work in our case. So a quick update and the problem was solved:

string realPath = app.Request.Path;
// if the length is only one character then we are at the root of the web and applicationPath
// has returned "\"  Otherwise, rip out the ApplicationPath
if (app.Request.ApplicationPath.Length > 1)
    realPath = realPath.Remove(0, app.Request.ApplicationPath.Length+1);
else
    realPath = realPath.Remove(0,1);

if(settings.IsExcludedPath(realPath)){
   // skip if the file path excludes compression
   return;
}

Hopefully this helps those of you that have seen this exception popup. Oh, and a special shout out to Ben for making a great module, and including the source too.

1 Comment

Comments have been disabled for this content.