我有一个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和response.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;
}
答案 0 :(得分:0)
您的语法对于集合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;
可能会生成异常,并且不会加载您的静态文件。
答案 1 :(得分:0)
花了更多时间解决问题后,我检查了服务器上的应用程序日志。我找到了罪魁祸首。
HttpModule引发未处理的异常,这就是导致请求完全失败的原因。