カスタム IHttpModule を作成しましたが、ソースに終了タグがない場合に問題が発生します。私はCMSでいくつかのページに出くわしました.aspxページがハンドラーのように使用され、htmlを閉じてajax経由でユーザーに応答を返す場所でこれを実行しています。
ここに私の情報源があります:
public class HideModule : IHttpModule
{
public void Dispose()
{
//Empty
}
public void Init(HttpApplication app)
{
app.ReleaseRequestState += new EventHandler(InstallResponseFilter);
}
// ---------------------------------------------
private void InstallResponseFilter(object sender, EventArgs e)
{
HttpResponse response = HttpContext.Current.Response;
string filePath = HttpContext.Current.Request.FilePath;
string fileExtension = VirtualPathUtility.GetExtension(filePath);
if (response.ContentType == "text/html" && fileExtension.ToLower() == ".aspx")
response.Filter = new PageFilter(response.Filter);
}
}
public class PageFilter : Stream
{
Stream responseStream;
long position;
StringBuilder responseHtml;
public PageFilter (Stream inputStream)
{
responseStream = inputStream;
responseHtml = new StringBuilder ();
}
//Other overrides here
public override void Write(byte[] buffer, int offset, int count)
{
string strBuffer = System.Text.UTF8Encoding.UTF8.GetString (buffer, offset, count);
Regex eof = new Regex ("</html>", RegexOptions.IgnoreCase);
if (!eof.IsMatch (strBuffer))
{
responseHtml.Append (strBuffer);
}
else
{
responseHtml.Append (strBuffer);
string finalHtml = responseHtml.ToString();
//Do replace here
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml);
responseStream.Write(data, 0, data.Length);
}
}
#endregion
}
ご覧のとおり、これは Write が最後に呼び出されたときにのみ置換を行うため、優れていますが、出力に終了 HTML タグがない場合は blammo.
私の最善の選択肢は、閉じている html が見つからない場合は、新しいフィルターを追加することさえしないことです。でも、そんなに早い段階で完全なストリームを傍受できるとは思いません。書き込みがストリームの最後にあることを検出する別の方法があることに失敗した場合は、html の終了タグを探す以外に?
前もって感謝します。