【问题标题】:IHttpModule Response.Filter Write with No Close HTMLIHttpModule Response.Filter 写入不关闭 HTML
【发布时间】:2011-07-13 21:03:54
【问题描述】:

我编写了一个自定义 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标签之外,还有另一种检测Write的方法是在流的末尾吗?

提前致谢。

【问题讨论】:

    标签: c# asp.net ihttpmodule response.filter


    【解决方案1】:

    好吧,如果是 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 2016-08-03
      • 2011-02-19
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多