HttpModule Filter_OnTransformString 导致一些静态文件失效(即 css, js

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

我有一个 HttpModule 来分析和监控网站。在此 HttpModule 中,它使用响应过滤器来修改响应主体并插入一段代码以将 javascript 代码加载到 text/html 内容中。

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;
}

查看 Chrome DevTools 中的网络流量,我看到 bootstrap.css、jquery-ui.min.css、jquery-3.1。1.js,和respond.js都失败了。

然而,其他 CSS 和 JS 文件都很好。例如,这里是 modernizr-2.8.3.js 的日志文件输出,后面是 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

我在这里遗漏了什么重要的东西吗?

更新:

目前,我围绕这个问题编写了如下代码:

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;
}

set output var:

的语法不正确
output = left + "<script type="text/javascript" src="/heartbeat.axd/script"></script>" + right;

连接的正确形式是:

output = left + "<script type='text/javascript' src='/heartbeat.axd/script'></script>" + right;

可能这会产生异常并且不会加载您的静态文件。

在花了更多时间解决该问题后,我检查了服务器上的应用程序日志。我找到了罪魁祸首。

HttpModule 抛出未处理的异常,这就是导致请求失败的原因。