Search code examples
javascriptc#asp.nethttpmodule

HttpModule Filter_OnTransformString causes some static files to fail (ie css, js


I have an HttpModule to analysis and monitoring of web sites. In this HttpModule, it makes use of a response filter to to modify response body and insert a fragment of code to load javascript code into text/html content.

private string Filter_OnTransformString(string output)
{
    Logger.Info("Filter_OnTransformString", "Enter method for " + Request.RawUrl);

    if (Response.ContentType != "text/html")
    {
        Logger.Info("Filter_OnTransformString", "Exiting for " + Response.ContentType + " MIME type for " + Request.RawUrl);
        return output;
    }

    if (output != null)
    {
        var pos = output.IndexOf("</body>", StringComparison.InvariantCultureIgnoreCase);
        Logger.Verbose("Filter_OnTransformString", "pos (of closing </body>) == " + pos);

        if (pos > -1)
        {
            var left = output.Substring(0, pos);
            var right = output.Substring(pos);

            output = left + "<script type=\"text/javascript\" src=\"/heartbeat.axd/script\"></script>" + right;
        }
    }
    else
    {
        Logger.Warning("Filter_OnTransformString", "output == null for " + Request.RawUrl);
    }

    Logger.Info("Filter_OnTransformString", "Exit method for " + Request.RawUrl);

    return output;
}

Looking at the network traffic in the Chrome DevTools, I see that bootstrap.css, jquery-ui.min.css, jquery-3.1.1.js, and respond.js all failed.

enter image description here

Yet, other CSS and JS files came down just fine. For example, here is the log file output for modernizr-2.8.3.js followed by the log file output for jquery-3.1.1.js.

11:19:31.1695   Info    Filter_OnTransformString    Enter method for /Scripts/modernizr-2.8.3.js
11:19:31.1695   Info    Filter_OnTransformString    Exiting for application/javascript MIME type for /Scripts/modernizr-2.8.3.js


11:19:31.5914   Info    Filter_OnTransformString    Enter method for /Scripts/jquery-3.1.1.js
11:19:31.5914   Info    Filter_OnTransformString    Exiting for application/javascript MIME type for /Scripts/jquery-3.1.1.js

Is there something critical I'm missing here?

Update:

At the moment, I've coded around the issue like this:

if (!Request.RawUrl.EndsWithAny(new[] { ".css", ".js" }, StringComparison.InvariantCultureIgnoreCase))
{
    Logger.Verbose("Application_BeginRequest", "Attaching Response.Filter to " + Request.RawUrl);
    ResponseFilterStream filter = new ResponseFilterStream(Response.Filter);
    filter.TransformString += Filter_OnTransformString;
    Response.Filter = filter;
}

Solution

  • After spending more time working around the problem, I checked the Application log on the server. I found the culprit.

    The HttpModule is throwing an unhandled exception and that is what's causing the request to simply fail.