ITPub博客

首页 > IT职业 > IT职场 > 一个页面标题和过滤输出的解决方案

一个页面标题和过滤输出的解决方案

IT职场 作者:amadan 时间:2021-09-09 09:41:41 0 删除 编辑

首先要提到一个东西:Response.Filter,它可以为你服务什么?

filter可以让你截取到最后的html输出,如果你的程序需要在输出之前,做一些处理,用这个比较方便。

 

 

第二个问题,在哪里,如何使用Response.Filter

这里使用上全局的Global.asax处理,在Global.asax的Application_BeginRequest事件里截取html

 

 

事件代码复杂?其实就一行:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.Filter = new HttpResponseFilter(HttpContext.Current.Response.Filter,new ReplaceTextList());
}

 

 

代码中的HttpResponseFilter类是什么?

说功能:这类主要实现的功能是,接替默认的Filter,然后换成自定义的Filter,方便处理自己要处理的事情。

哪来的:由于Response.Filter 是一个Stream类,所以新类HttpResponseFilter需要继承自Stream,然后复写Write方法,实现自定义方法即可。

 

 

复写代码示例:

图片描述

public override void Write(byte[] buffer, int offset, int count)
{
            //读出写的文字

            byte[] data = new byte[count];

            Buffer.BlockCopy(buffer, offset, data, 0, count);

            string inputText = Encoding.UTF8.GetString(data);

            //开始替换
            if (replaceTextList != null && replaceTextList.Count > 0)
            {
                foreach (KeyValuePair values in replaceTextList)
                {
                    inputText = Regex.Replace(inputText, values.Key, values.Value, RegexOptions.Singleline);
                }
                replaceTextList.Clear();
            }
            replaceTextList = null;

            //将替换后的写入response
            byte[] newdata = Encoding.UTF8.GetBytes(inputText);
            filterStream.Write(newdata, 0, newdata.Length);
}

图片描述

 

代码解读:

图片描述

分三步走:

1:读取原文本内容

2:然后替换修改成自己的内容

3:写回去输出

注意事项:要注意网站编码是UTF8还是GB2312

重点是:我扩展了替换那一块,我用了一个Dictionary 

然后循环替换,当然支持正则,所以替换的原始文字和替换后的文字就对应上两个string上了

具体扩展应用见下篇文章。
图片描述

 

扩展的小说明:

为了可扩展与方便大伙,我定义了一个抽象类,先实现了三个正则用于截取标题,说明,和关键字,具体应用还是见下文。

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2310/viewspace-2811459/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-06

  • 博文量
    200
  • 访问量
    14416