IHttpModule响应.过滤写没有关闭HTML

本文关键字:HTML 响应 过滤 IHttpModule | 更新日期: 2023-09-27 18:02:31

我写了一个自定义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标记,那么

如果没有找到关闭html,我最好的选择是甚至不添加新的过滤器。但我觉得我没办法这么早截住全部消息。失败是有另一种方法来检测写是在流的末尾除了寻找关闭html标签?

IHttpModule响应.过滤写没有关闭HTML

如果是WebForms,你应该能够在你的InstallResponseFilter函数中做这样的事情:

if(Application.Context.CurrentHandler is System.Web.UI.Page
                    && Application.Request["HTTP_X_MICROSOFTAJAX"] == null
                    && Application.Request.Params["_TSM_CombinedScripts_"] == null)
{
response.Filter=new PageFilter(response.Filter);
}