首页 > 其他分享 >一个页面标题和过滤输出的解决方案(上)

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

时间:2022-09-29 23:07:57浏览次数:47  
标签:replaceTextList 解决方案 替换 Filter 过滤 inputText byte Response 页面

首先要提到一个东西: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<string, string> 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, string> 

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

具体扩展应用见下篇文章。

 

扩展的小说明:

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

 

标签:replaceTextList,解决方案,替换,Filter,过滤,inputText,byte,Response,页面
From: https://blog.51cto.com/cyq1162/5724354

相关文章